package com.example.glgk.service.indicator;

import com.example.glgk.dto.indicator.*;
import com.example.glgk.dto.indicatorAnalysisDto.DepartmentDto;
import com.example.glgk.dto.indicatorReport.IndicatorReportDto;
import com.example.glgk.entity.DepartmentIndicatorEntity;
import com.example.glgk.entity.ElementDataEntity;
import com.example.glgk.entity.IndicatorDataEntity;
import com.example.glgk.entity.indicator.AnnexDataEntity;
import com.example.glgk.mapper.ElementDataMapper;
import com.example.glgk.mapper.ReportMapper;
import com.example.glgk.mapper.ReportTaskMapper;
import com.example.glgk.mapper.indicator.IndicatorCalculateMapper;
import com.example.glgk.mapper.indicatorReport.IndicatorReportMapper;
import com.example.glgk.service.gather.GatherCommonService;
import com.example.glgk.utils.Calculator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lxk
 */
@Service
@Slf4j
public class IndicatorCalculateService {

    private final static String upIndicatorGuide = "1";
    private final static String downIndicatorGuide = "2";

    @Autowired
    IndicatorCalculateMapper indicatorCalculateMapper;

    @Autowired
    GatherCommonService gatherCommonService;

    @Autowired
    ElementDataMapper elementDataMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ReportTaskMapper reportTaskMapper;

    @Autowired
    private IndicatorReportMapper indicatorReportMapper;


    public List<CommonDto> systemGenerate() {
        List<CommonDto> result = new ArrayList<>();
        //求出各个分类下的指标数
        result = indicatorCalculateMapper.systemGenerate();
        CommonDto commonDto = CommonDto.builder().name("监测指标数量").quantity(indicatorCalculateMapper.queryMonitorNumber()).build();
        result.add(commonDto);
        return result;
    }

    public List<AnnexDataDto> annexData(IndicatorCalculateDto indicatorCalculateDto) {
        setYears(indicatorCalculateDto);
        List<AnnexDataEntity> list = indicatorCalculateMapper.annexData(indicatorCalculateDto);
        if (CollectionUtils.isNotEmpty(list)) {
            List<AnnexDataDto> result = new ArrayList<>();
            Map<String, List<AnnexDataEntity>> collect = list.stream().collect(Collectors.groupingBy(AnnexDataEntity::getName));
            //todo 先这样 速度慢再优化
            for (String name : collect.keySet()) {
                AnnexDataDto annexDataDto = AnnexDataDto.builder().indicatorXh(collect.get(name).get(0).getXh())
                        .indicatorName(name)
                        .indicatorUnit(collect.get(name).get(0).getUnit())
                        .responsibleDepartment(collect.get(name).get(0).getResponsibleDepartment())
                        .leader(collect.get(name).get(0).getLeader())
                        .annexYearDtos(new ArrayList<>())
                        .deptName(indicatorCalculateDto.getUserInfo().getWardName())
                        .build();
                for (AnnexDataEntity annexDataEntity : collect.get(name)) {
                    AnnexYearDto annexYearDto = AnnexYearDto.builder().time(annexDataEntity.getTime()).indicatorValue(annexDataEntity.getValue()).fullValue(annexDataEntity.getFullValue()).yoyValue(annexDataEntity.getYoyValue()).build();
                    annexDataDto.getAnnexYearDtos().add(annexYearDto);
                }
                //好像要按照时间倒序
                annexDataDto.setAnnexYearDtos(annexDataDto.getAnnexYearDtos().stream().sorted(Comparator.comparing(AnnexYearDto::getTime).reversed()).collect(Collectors.toList()));
                result.add(annexDataDto);
            }
            result = result.stream().sorted(Comparator.comparing(AnnexDataDto::getIndicatorXh))
                    .collect(Collectors.toList());
            return result;
        } else {
            throw new RuntimeException("未查询到当前年份数据！");
        }
    }

    /**
     * 重构附件一方法
     *
     * @param indicatorCalculateDto
     * @return
     */
    public List<AnnexDataDto> annexIndicatorData(IndicatorCalculateDto indicatorCalculateDto) {

        List<AnnexDataDto> annexDataDtoList = new ArrayList<>();

        Year currentYear = Year.now();//今年

        //查询所有指标
        List<IndicatorDataEntity> allIndicator = indicatorCalculateMapper.selectAll(indicatorCalculateDto);
        //对所有涉及到的id进行去重
        List<String> elementIds = gatherCommonService.getAllElementIds(allIndicator);
        //查询元素定义表，确定元素数据来源 天表、月表、手填表等
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> dayTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "1".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> monthTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "2".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> handTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "3".equals(s.getDataTable())).collect(Collectors.toList());

        List<DepartmentIndicatorEntity> departmentIndicatorEntityList = new ArrayList<>();// 存放当前时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityLastList = new ArrayList<>();// 存放去年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityBeforeList = new ArrayList<>();// 存放前年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityPreviousList = new ArrayList<>();// 存放大前年时间的所有的天表、月表、手填表数据

        //查出天表数据 求的是指定时间区间的 天表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(dayTable)) {
            indicatorCalculateDto.setElementIds(dayTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> curDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityList.addAll(curDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> lastDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityLastList.addAll(lastDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> beforeDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityBeforeList.addAll(beforeDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> previousDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityPreviousList.addAll(previousDayData);
        }

        List<String> groupTimes;
        //查出月表数据 求的是指定时间区间的 月表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(monthTable)) {

            indicatorCalculateDto.setElementIds(monthTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> monthData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityList.addAll(monthData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> monthLastData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityLastList.addAll(monthLastData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> monthBeforeData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityBeforeList.addAll(monthBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> monthPreviousData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityPreviousList.addAll(monthPreviousData);

        }

        //查出手填表数据 求的是指定时间区间的 手填表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(handTable)) {
            indicatorCalculateDto.setElementIds(handTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<String> taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityList.addAll(handTableData);


            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableLastData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableLastData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityLastList.addAll(handTableLastData);


            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableBeforeData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableBeforeData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityBeforeList.addAll(handTableBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTablePreviousData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTablePreviousData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityPreviousList.addAll(handTablePreviousData);
        }

        Map<String, String> mapValue = new HashMap<>();
        Map<String, String> mapLastValue = new HashMap<>();
        Map<String, String> mapBeforeValue = new HashMap<>();
        Map<String, String> mapPreviousValue = new HashMap<>();
        mapValue = departmentIndicatorEntityList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapLastValue = departmentIndicatorEntityLastList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapBeforeValue = departmentIndicatorEntityBeforeList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapPreviousValue = departmentIndicatorEntityPreviousList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));

        for (IndicatorDataEntity entity : allIndicator) {
            //解析当前指标的公式，通过元素值计算指标值
            String formula = entity.getCalculationFormulaId();
            String indexValue = Calculator.conversionToSting(formula, mapValue);
            String indexLastValue = Calculator.conversionToSting(formula, mapLastValue);
            String indexBeforeValue = Calculator.conversionToSting(formula, mapBeforeValue);
            String indexPreviousValue = Calculator.conversionToSting(formula, mapPreviousValue);


            AnnexYearDto annexYearDto = new AnnexYearDto();
            AnnexYearDto lastAnnexYearDto = new AnnexYearDto();
            AnnexYearDto beforeAnnexYearDto = new AnnexYearDto();

            //  设置近三年满分值
            annexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            lastAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            beforeAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));

            //  设置近三年指标值
            BigDecimal indexDecimal = new BigDecimal(indexValue.equals("-") ? "0" : indexValue);
            BigDecimal lastDecimal = new BigDecimal(indexLastValue.equals("-") ? "0" : indexLastValue);
            BigDecimal beforeDecimal = new BigDecimal(indexBeforeValue.equals("-") ? "0" : indexBeforeValue);
            annexYearDto.setIndicatorValue(indexDecimal);
            lastAnnexYearDto.setIndicatorValue(lastDecimal);
            beforeAnnexYearDto.setIndicatorValue(beforeDecimal);

            //设置近三年时间
            annexYearDto.setTime(currentYear.toString());
            lastAnnexYearDto.setTime(currentYear.minusYears(1).toString());
            beforeAnnexYearDto.setTime(currentYear.minusYears(2).toString());


            //设置近三年同比增幅
            String yoyValue = calculateGrowthRate(indexValue, indexLastValue);
            String lastYoyValue = calculateGrowthRate(indexLastValue, indexBeforeValue);
            String beforeYoyValue = calculateGrowthRate(indexBeforeValue, indexPreviousValue);
            annexYearDto.setYoyValue(new BigDecimal(yoyValue.equals("-") ? "0" : yoyValue));
            lastAnnexYearDto.setYoyValue(new BigDecimal(lastYoyValue.equals("-") ? "0" : lastYoyValue));
            beforeAnnexYearDto.setYoyValue(new BigDecimal(beforeYoyValue.equals("-") ? "0" : beforeYoyValue));


            AnnexDataDto annexDataDto = new AnnexDataDto();
            annexDataDto.setDeptName(indicatorCalculateDto.getUserInfo().getWardName());
            annexDataDto.setIndicatorName(entity.getIndexName());
            annexDataDto.setIndicatorUnit(entity.getIndexUnit());
            annexDataDto.setIndicatorXh(entity.getRank());
            annexDataDto.setLeader(entity.getFgld());
            annexDataDto.setResponsibleDepartment(entity.getZrbm());
            annexDataDto.getAnnexYearDtos().add(annexYearDto);
            annexDataDto.getAnnexYearDtos().add(lastAnnexYearDto);
            annexDataDto.getAnnexYearDtos().add(beforeAnnexYearDto);

            annexDataDtoList.add(annexDataDto);

        }


        return annexDataDtoList;
    }


    public Map<String, List<IndicatorOverviewDto>> getOverviewData(IndicatorCalculateDto indicatorCalculateDto) {
        Map<String, List<IndicatorOverviewDto>> resultMap = new HashMap<>();
        //todo 把时间、dept_name符合的都查询出来，然后计算业务趋势 记得吧指标导向=0 的排除掉 不参与计算
        List<IndicatorOverviewDto> result = indicatorCalculateMapper.getOverviewData(indicatorCalculateDto);
        //判断是否监测指标查询
        if ("0".equals(indicatorCalculateDto.getIsMonitor())) {
            //查询的就是非监测
            result = result.stream().filter(x -> null == x.getFullValue()).collect(Collectors.toList());
            //非监测指标且为科室的 需要计算持平指标
            if (!"JXZB".equals(indicatorCalculateDto.getUserInfo().getParentDepartmentId()) && !"ZNBM".equals(indicatorCalculateDto.getUserInfo().getParentDepartmentId())) {
                //持平数据
                List<IndicatorOverviewDto> levelDatas = new ArrayList<>();
                for (IndicatorOverviewDto indicatorOverviewDto : result) {
                    boolean isProgress = false;
                    if ("month".equals(indicatorCalculateDto.getTimeNode())) {
                        isProgress = indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) == 0;
                    } else {
                        isProgress = indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) == 0;
                    }
                    if (isProgress) {
                        levelDatas.add(indicatorOverviewDto);
                    }
                }
                resultMap.put("level", levelDatas);
                result = result.stream().filter(x -> !levelDatas.contains(x)).collect(Collectors.toList());
            }
        } else {
            //查询的就是监测
            result = result.stream().filter(x -> x.getFullValue() != null).collect(Collectors.toList());
            //满分指标数据 指标导向为1 指标值 > = 满分值   指标导向为2 指标值 < = 满分值
            //只有监测指标才有满分值
            List<IndicatorOverviewDto> fullValues = result.stream()
                    .filter(x -> (null != x.getFullValue() && x.getFullValue().compareTo(BigDecimal.ZERO) != 0)
                            && (upIndicatorGuide.equals(x.getIndicatorGuide()) && null != x.getIndicatorValue() && x.getIndicatorValue().compareTo(x.getFullValue()) >= 0)
                            || (downIndicatorGuide.equals(x.getIndicatorGuide()) && null != x.getIndicatorValue() && x.getIndicatorValue().compareTo(x.getFullValue()) <= 0))
                    .collect(Collectors.toList());
            resultMap.put("full", fullValues);
            result = result.stream().filter(x -> !fullValues.contains(x)).collect(Collectors.toList());
        }

        List<IndicatorOverviewDto> upDatas = new ArrayList<>();
        List<IndicatorOverviewDto> downDatas = new ArrayList<>();

        // 计算  未达到满分的   进步 / 退步 监测指标
        for (IndicatorOverviewDto indicatorOverviewDto : result) {
            boolean isProgress = false;
            if (upIndicatorGuide.equals(indicatorOverviewDto.getIndicatorGuide())) {
                if ("month".equals(indicatorCalculateDto.getTimeNode())) {
                    isProgress = indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) > 0;
                } else {
                    isProgress = indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) > 0;
                }
            } else if (downIndicatorGuide.equals(indicatorOverviewDto.getIndicatorGuide())) {
                if ("month".equals(indicatorCalculateDto.getTimeNode())) {
                    isProgress = indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) < 0;
                } else {
                    isProgress = indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) < 0;
                }
            }
            if (isProgress) {
                upDatas.add(indicatorOverviewDto);
            } else {
                downDatas.add(indicatorOverviewDto);
            }
        }
        resultMap.put("up", upDatas);
        resultMap.put("down", downDatas);
        return resultMap;
    }

    public List<DataListDto> getDataList(IndicatorCalculateDto indicatorCalculateDto) {
        String time = indicatorCalculateDto.getStartTime().equals(indicatorCalculateDto.getEndTime()) ? indicatorCalculateDto.getStartTime() : indicatorCalculateDto.getStartTime() + "~" + indicatorCalculateDto.getEndTime();
        Map<String, List<IndicatorOverviewDto>> overviewData = getOverviewData(indicatorCalculateDto);
        String key = indicatorCalculateDto.getFlag() == 0 ? "full" : indicatorCalculateDto.getFlag() == 1 ? "up" : "down";
        if (CollectionUtils.isEmpty(overviewData.get(key))) {
            return null;
        }
        List<DataListDto> result = new ArrayList<>();
        //todo 不应该用name的，应该用id，后续改
        List<String> ids = overviewData.get(key).stream().map(IndicatorOverviewDto::getId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        indicatorCalculateDto.setIndicatorIds(ids);
        //todo union all查询出三个时间段的数据之后，然后根据指标项进行分组，然后遍历填充数据
        List<IndicatorOverviewDto> dataList = indicatorCalculateMapper.getDataList(indicatorCalculateDto);
        //得到是在总趋势下的各科科室数据，然后在进行退步 /满分 /进步的科室
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        Map<String, List<IndicatorOverviewDto>> collect = dataList.stream().collect(Collectors.groupingBy(IndicatorOverviewDto::getIndicatorName));
        for (String name : collect.keySet()) {
            List<IndicatorOverviewDto> indicatorOverviewDtos = collect.get(name);
            DataListDto dataListDto = DataListDto.builder()
                    .indicatorName(name)
                    .dataDetails(new DataDetail())
                    .build();
            DataDetail dataDetail = new DataDetail();
            //todo 这里是否不需要分临床 交给setDataDetail()这个方法区分
            List<IndicatorOverviewDto> clinicalList = indicatorOverviewDtos.stream().filter(x -> null != x.getIsClinical()).collect(Collectors.toList());
            setDataDetail(dataDetail, clinicalList, indicatorCalculateDto.getTimeNode(), time);
            dataListDto.setDataDetails(dataDetail);
            result.add(dataListDto);
        }
        return result;
    }

    /**
     * 设置近三年的年份
     *
     * @param indicatorCalculateDto
     */
    private void setYears(IndicatorCalculateDto indicatorCalculateDto) {
        SimpleDateFormat sdf;
        if (indicatorCalculateDto.getTimeNode().equals("month")) {
            sdf = new SimpleDateFormat("yyyy-MM");
        } else {
            sdf = new SimpleDateFormat("yyyy");
        }

        String startTime = indicatorCalculateDto.getStartTime();
        Date date = null;
        try {
            date = sdf.parse(startTime);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int startYear = cal.get(Calendar.YEAR);
        int previousYear = startYear - 1;
        int twoYearsAgoYear = startYear - 2;
        List<Integer> years = Arrays.asList(startYear, previousYear, twoYearsAgoYear);
        indicatorCalculateDto.setYears(years);
    }


    public DataDetail setDataDetail(DataDetail dataDetail, List<IndicatorOverviewDto> clinicalList, String timeNode, String time) {
        List<AnnexDataDto> tableList1 = dataDetail.getTableList1();
        List<AnnexDataDto> tableList2 = dataDetail.getTableList2();
        List<AnnexDataDto> tableList3 = dataDetail.getTableList3();
        List<AnnexDataDto> tableList4 = dataDetail.getTableList4();
        List<AnnexDataDto> tableList5 = dataDetail.getTableList5();
        List<AnnexDataDto> tableList6 = dataDetail.getTableList6();
        List<AnnexDataDto> tableList7 = dataDetail.getTableList7();
        List<AnnexDataDto> tableList8 = dataDetail.getTableList8();
        //todo 待优化的点
        // 1、因为数据是根据指标分组的，所以指标导向是一样的，就没必要循环一次判断一次指标导向
        // 2、组装数据的步骤重复啰嗦，需要优化
        // 3、clinicalList就是单个指标的所有符合条件的科室的历年数据，所以到表格层面 那就是对科室分组
        // 4、科室要排除其他(仅统计门诊人次)
        // 5、在判断属于哪个集合的时候，满分科室的优先级 > 趋势科室 如果是满分科室就不管进步/退步/持平
        Map<String, List<IndicatorOverviewDto>> collect = clinicalList.stream().collect(Collectors.groupingBy(IndicatorOverviewDto::getDeptName));
        for (String deptName : collect.keySet()) {
            List<IndicatorOverviewDto> indicatorOverviewDtos = collect.get(deptName);
            if (CollectionUtils.isEmpty(indicatorOverviewDtos)) {
                continue;
            }
            indicatorOverviewDtos = indicatorOverviewDtos.stream().sorted(Comparator.comparing(IndicatorOverviewDto::getTime).reversed()).collect(Collectors.toList());
            //按照time排序 如果没有当前参数time的数据，那就代表这条数据没意义 过滤掉
            IndicatorOverviewDto indicatorOverviewDto = indicatorOverviewDtos.get(0);
            if (!indicatorOverviewDto.getTime().equals(time)) {
                continue;
            }
            AnnexDataDto annexDataDto = AnnexDataDto.builder().indicatorXh(indicatorOverviewDto.getIndicatorXh())
                    .indicatorName(indicatorOverviewDto.getIndicatorName())
                    .indicatorUnit(indicatorOverviewDto.getUnit())
                    .responsibleDepartment(indicatorOverviewDto.getResponsibleDepartment())
                    .leader(indicatorOverviewDto.getLeader())
                    .annexYearDtos(new ArrayList<>())
                    .deptName(indicatorOverviewDto.getDeptName())
                    .build();
            //组装多级表头数据
            for (IndicatorOverviewDto dto : indicatorOverviewDtos) {
                AnnexYearDto annexYearDto = AnnexYearDto.builder().time(dto.getTime()).indicatorValue(dto.getIndicatorValue()).fullValue(dto.getFullValue()).yoyValue(dto.getYoyValue()).momValue(dto.getMomValue()).build();
                annexDataDto.getAnnexYearDtos().add(annexYearDto);
            }
            //todo 如果说有数据 当前时间没数据，那这次循环就可以跳过 不展示
            //如果indicatorOverviewDto的指标值 >= 满分值 且指标导向为upIndicatorGuide 且是否临床为1 那就是满分的手术科室数据 如果是否临床为0 那就是满分的非手术科室
            //如果indicatorOverviewDto的指标值 <= 满分值 downIndicatorGuide 且是否临床为1 那也是满分的手术科室 如果是否临床为0 那就是满分的非手术科室
            if (upIndicatorGuide.equals(indicatorOverviewDto.getIndicatorGuide())) {
                if (indicatorOverviewDto.getFullValue() != null && indicatorOverviewDto.getIndicatorValue().compareTo(indicatorOverviewDto.getFullValue()) >= 0) {
                    if (indicatorOverviewDto.getIsClinical().equals(1)) {
                        //满分手术科室
                        tableList7.add(annexDataDto);
                    } else {
                        //满分非手术科室
                        tableList8.add(annexDataDto);
                    }
                    continue;
                }
                if ("month".equals(timeNode)) {
                    if (indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) > 0) {
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //进步且手术
                            tableList6.add(annexDataDto);
                        } else {
                            //进步且非手术
                            tableList5.add(annexDataDto);
                        }
                    } else if (indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) < 0) {
                        //退步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //退步且手术
                            tableList1.add(annexDataDto);
                        } else {
                            //退步非手术
                            tableList2.add(annexDataDto);
                        }
                    } else {
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //持平且手术
                            tableList3.add(annexDataDto);
                        } else {
                            //持平非手术
                            tableList4.add(annexDataDto);
                        }
                    }
                } else if ("year".equals(timeNode)) {
                    if (indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) > 0) {
                        //进步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //进步且手术
                            tableList6.add(annexDataDto);
                        } else {
                            //进步且非手术
                            tableList5.add(annexDataDto);
                        }
                    } else if (indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) < 0) {
                        //退步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //退步且手术
                            tableList1.add(annexDataDto);
                        } else {
                            //退步非手术
                            tableList2.add(annexDataDto);
                        }
                    } else {
                        //持平
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //持平且手术
                            tableList3.add(annexDataDto);
                        } else {
                            //持平非手术
                            tableList4.add(annexDataDto);
                        }
                    }
                }
            } else if (downIndicatorGuide.equals(indicatorOverviewDto.getIndicatorGuide())) {
                if (indicatorOverviewDto.getFullValue() != null && indicatorOverviewDto.getIndicatorValue().compareTo(indicatorOverviewDto.getFullValue()) <= 0) {
                    if (indicatorOverviewDto.getIsClinical().equals(1)) {
                        //满分手术科室
                        tableList7.add(annexDataDto);
                    } else {
                        //满分非手术科室
                        tableList8.add(annexDataDto);
                    }
                    continue;
                }
                if ("month".equals(timeNode)) {
                    if (indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) > 0) {
                        //退步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //退步且手术
                            tableList1.add(annexDataDto);
                        } else {
                            //退步非手术
                            tableList2.add(annexDataDto);
                        }
                    } else if (indicatorOverviewDto.getMomValue() != null && indicatorOverviewDto.getMomValue().compareTo(BigDecimal.ZERO) < 0) {
                        //进步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //进步且手术
                            tableList6.add(annexDataDto);
                        } else {
                            //进步且非手术
                            tableList5.add(annexDataDto);
                        }
                    } else {
                        //持平
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //持平且手术
                            tableList3.add(annexDataDto);
                        } else {
                            //持平非手术
                            tableList4.add(annexDataDto);
                        }
                    }
                } else if ("year".equals(timeNode)) {
                    if (indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) > 0) {
                        //退步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //退步且手术
                            tableList1.add(annexDataDto);
                        } else {
                            //退步非手术
                            tableList2.add(annexDataDto);
                        }
                    } else if (indicatorOverviewDto.getYoyValue() != null && indicatorOverviewDto.getYoyValue().compareTo(BigDecimal.ZERO) < 0) {
                        //进步
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //进步且手术
                            tableList6.add(annexDataDto);
                        } else {
                            //进步且非手术
                            tableList5.add(annexDataDto);
                        }
                    } else {
                        //持平
                        if (indicatorOverviewDto.getIsClinical().equals(1)) {
                            //持平且手术
                            tableList3.add(annexDataDto);
                        } else {
                            //持平非手术
                            tableList4.add(annexDataDto);
                        }
                    }
                }
            }
        }
        dataDetail.setTableList1(tableList1);
        dataDetail.setTableList2(tableList2);
        dataDetail.setTableList3(tableList3);
        dataDetail.setTableList4(tableList4);
        dataDetail.setTableList5(tableList5);
        dataDetail.setTableList6(tableList6);
        dataDetail.setTableList7(tableList7);
        dataDetail.setTableList8(tableList8);
        return dataDetail;
    }

    /**
     * @param indicatorCalculateDto
     * @return
     * @Description: 附件2, 3的数据
     */
    public List<AnnexDataDto> otherAnnexData(IndicatorCalculateDto indicatorCalculateDto) {
        List<IndicatorOverviewDto> dataList = indicatorCalculateMapper.getDataList2(indicatorCalculateDto);
        if ("0".equals(indicatorCalculateDto.getIsMonitor())) {
            //查询的就是非重点 满分值 为空
            dataList = dataList.stream().filter(x -> null == x.getFullValue()).collect(Collectors.toList());
        } else {
            //查询的就是重点 满分值 不为空 的
            dataList = dataList.stream().filter(x -> null != x.getFullValue()).collect(Collectors.toList());
        }
        List<AnnexDataDto> annexDataDtos = new ArrayList<>();
        //根据指标名字分组
        Map<String, List<IndicatorOverviewDto>> collect = dataList.stream().collect(Collectors.groupingBy(IndicatorOverviewDto::getIndicatorName));
        for (String indicatorName : collect.keySet()) {
            List<IndicatorOverviewDto> indicatorOverviewDtos = collect.get(indicatorName);
            IndicatorOverviewDto indicatorOverviewDto = indicatorOverviewDtos.get(0);
            AnnexDataDto annexDataDto = AnnexDataDto.builder().indicatorXh(indicatorOverviewDto.getIndicatorXh())
                    .indicatorName(indicatorOverviewDto.getIndicatorName())
                    .indicatorUnit(indicatorOverviewDto.getUnit())
                    .responsibleDepartment(indicatorOverviewDto.getResponsibleDepartment())
                    .deptName(indicatorOverviewDto.getDeptName())
                    .leader(indicatorOverviewDto.getLeader())
                    .annexYearDtos(new ArrayList<>())
                    .build();
            for (IndicatorOverviewDto dto : indicatorOverviewDtos) {
                AnnexYearDto annexYearDto = AnnexYearDto.builder().time(dto.getTime()).indicatorValue(dto.getIndicatorValue()).fullValue(dto.getFullValue()).yoyValue(dto.getYoyValue()).momValue(dto.getMomValue()).build();
                annexDataDto.getAnnexYearDtos().add(annexYearDto);
            }
            annexDataDtos.add(annexDataDto);
        }
        annexDataDtos = annexDataDtos.stream().sorted(Comparator.comparing(AnnexDataDto::getIndicatorXh))
                .collect(Collectors.toList());
        return annexDataDtos;
    }


    /**
     * 监测指标整体情况
     *
     * @param indicatorCalculateDto
     * @return
     */
    public Map<String, List<IndicatorOverviewDto>> getMonitorIndicatorOverviewData(IndicatorCalculateDto indicatorCalculateDto) {

        //重点监测指标
        List<IndicatorDataEntity> keyIndicatorList = indicatorCalculateMapper.getKeyIndicator(indicatorCalculateDto);
        //非监测指标
        List<IndicatorDataEntity> otherIndicatorList = indicatorCalculateMapper.getOtherKeyIndicator(indicatorCalculateDto);

        List<IndicatorDataEntity> allIndicatorList = new ArrayList<>();
        allIndicatorList.addAll(keyIndicatorList);
        allIndicatorList.addAll(otherIndicatorList);

        //筛选前端传入的指标
        List<String> indicatorIds = indicatorCalculateDto.getIndicatorIds();

        if (indicatorIds != null && indicatorIds.size() > 0){
            IndicatorReportDto indicatorReportDto = new IndicatorReportDto();
            indicatorReportDto.setIndicatorXh(indicatorIds.get(0));
            IndicatorDataEntity indicatorByXh = indicatorReportMapper.getIndicatorByXh(indicatorReportDto);
            String id = indicatorByXh.getId();
            allIndicatorList = allIndicatorList.stream().filter(x -> id.contains(x.getId())).collect(Collectors.toList());
            keyIndicatorList = keyIndicatorList.stream().filter(x -> id.contains(x.getId())).collect(Collectors.toList());
            otherIndicatorList = otherIndicatorList.stream().filter(x -> id.contains(x.getId())).collect(Collectors.toList());
        }

        List<String> times = indicatorCalculateDto.getTimes();
        List<String> yoyTimes = getYoyTime(times);//获取同比时间集合
        //对所有涉及到的id进行去重
        List<String> elementIds = gatherCommonService.getAllElementIds(allIndicatorList);
        //查询元素定义表，确定元素数据来源 天表、月表、手填表等
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> dayTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "1".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> monthTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "2".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> handTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "3".equals(s.getDataTable())).collect(Collectors.toList());

        List<DepartmentIndicatorEntity> departmentIndicatorEntityList = new ArrayList<>();// 存放当前时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityYoyList = new ArrayList<>();// 存放同比时间的所有的天表、月表、手填表数据

        //查出天表数据 求的是指定时间区间的 天表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(dayTable)) {
            indicatorCalculateDto.setElementIds(dayTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            int size = indicatorCalculateDto.getTimes().size();
            indicatorCalculateDto.setStartTime(indicatorCalculateDto.getTimes().get(0));
            indicatorCalculateDto.setEndTime(indicatorCalculateDto.getTimes().get(size - 1));
            List<DepartmentIndicatorEntity> dayData = indicatorCalculateMapper.queryEscalationGroupByDay(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityList.addAll(dayData);

            size = yoyTimes.size();
            indicatorCalculateDto.setStartTime(yoyTimes.get(0));
            indicatorCalculateDto.setEndTime(yoyTimes.get(size - 1));
            List<DepartmentIndicatorEntity> dayYoyData = indicatorCalculateMapper.queryEscalationGroupByDay(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityYoyList.addAll(dayYoyData);
        }


        List<String> groupTimes;
        //查出月表数据 求的是指定时间区间的 月表数据之和（月表每个月数据就一条 求和与不求和没有区别）
        if (!org.springframework.util.CollectionUtils.isEmpty(monthTable)) {

            indicatorCalculateDto.setElementIds(monthTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            groupTimes = times.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            List<DepartmentIndicatorEntity> monthData = indicatorCalculateMapper.queryEscalationNew(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityList.addAll(monthData);

            groupTimes = yoyTimes.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            List<DepartmentIndicatorEntity> monthYoyData = indicatorCalculateMapper.queryEscalationNew(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityYoyList.addAll(monthYoyData);

        }

        //查出手填表数据 求的是指定时间区间的 手填表数据之和（手填表每个月数据就一条 求和与不求和没有区别）
        if (!org.springframework.util.CollectionUtils.isEmpty(handTable)) {
            indicatorCalculateDto.setElementIds(handTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            groupTimes = times.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            List<String> taskIds = reportTaskMapper.selectReportTasks(groupTimes, indicatorCalculateDto.getUserInfo().getWardName(), indicatorCalculateDto.getUserInfo().getParentDepartmentId());
            List<DepartmentIndicatorEntity> handTableData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableData = reportMapper.queryAnalysisReport(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityList.addAll(handTableData);


            groupTimes = yoyTimes.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            taskIds = reportTaskMapper.selectReportTasks(groupTimes, indicatorCalculateDto.getUserInfo().getWardName(), indicatorCalculateDto.getUserInfo().getParentDepartmentId());
            List<DepartmentIndicatorEntity> handTableYoyData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableYoyData = reportMapper.queryAnalysisReport(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityYoyList.addAll(handTableYoyData);
        }


        Map<String, String> mapValue = new HashMap<>();
        Map<String, String> mapYoyValue = new HashMap<>();
        mapValue = departmentIndicatorEntityList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapYoyValue = departmentIndicatorEntityYoyList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));

        Map<String, List<IndicatorOverviewDto>> result = new HashMap<>();
        List<IndicatorOverviewDto> fullList = new ArrayList<>();
        List<IndicatorOverviewDto> downList = new ArrayList<>();
        List<IndicatorOverviewDto> upList = new ArrayList<>();

        //用来存储特殊指标 满分或者退步的子指标
        List<IndicatorOverviewDto> otherFull = new ArrayList<>();
        List<IndicatorOverviewDto> otherDown = new ArrayList<>();
        List<IndicatorOverviewDto> otherUp = new ArrayList<>();

        double range = 0.0;
        boolean flag = true;
        Set<String> validIndexCodes1 = new HashSet<>(Arrays.asList("10.", "45."));
        Set<String> validIndexCodes2 = new HashSet<>(Arrays.asList("13."));
        Set<String> validIndexCodes3 = new HashSet<>(Arrays.asList("38.", "39.", "40.", "41."));
        Set<String> validIndexCodes4 = new HashSet<>(Arrays.asList("48."));

        for (IndicatorDataEntity entity : keyIndicatorList) {

            //解析当前指标的公式，通过元素值计算指标值
            String formula = entity.getCalculationFormulaId();
            String indexValue = Calculator.conversionToSting(formula, mapValue);//当前指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
            String indexYoyValue = Calculator.conversionToSting(formula, mapYoyValue);//同期指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值

            double mfz = entity.getMfz();
            String dx = entity.getDx();
            BigDecimal value = new BigDecimal(indexValue == "-" ? "0" : indexValue);
            BigDecimal yoyValue = new BigDecimal(indexYoyValue == "-" ? "0" : indexYoyValue);
            BigDecimal mfzValue = BigDecimal.valueOf(mfz);

            String ratio = calculateGrowthRate(indexValue, indexYoyValue);
            ratio = ratio.equals("-") ? "0" : ratio;

            IndicatorOverviewDto indicatorOverviewDto = new IndicatorOverviewDto();
            indicatorOverviewDto.setIndicatorXh(Integer.valueOf(entity.getId()));
            indicatorOverviewDto.setIndexCode(entity.getIndexCode());
            indicatorOverviewDto.setIndicatorName(entity.getIndexName());
            indicatorOverviewDto.setUnit(entity.getIndexUnit());
            indicatorOverviewDto.setTime(times.get(0) + "~" + times.get(times.size() - 1));
            indicatorOverviewDto.setIndicatorValue(value);
            indicatorOverviewDto.setFullValue(mfzValue);
            indicatorOverviewDto.setYoyValue(new BigDecimal(ratio));
            indicatorOverviewDto.setResponsibleDepartment(entity.getZrbm());
            indicatorOverviewDto.setLeader(entity.getFgld());
            indicatorOverviewDto.setIds(entity.getIds());
            indicatorOverviewDto.setCalculationFormulaId(entity.getCalculationFormulaId());
            indicatorOverviewDto.setDx(entity.getDx());


            //计算特殊指标10 和 45
            if (validIndexCodes1.contains(entity.getIndexCode())) {
                List<IndicatorOverviewDto> tempOtherFull = new ArrayList<>();
                List<IndicatorOverviewDto> tempOtherDown = new ArrayList<>();
                List<IndicatorDataEntity> mfFullList = new ArrayList<>();
                List<IndicatorDataEntity> mfIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().startsWith(entity.getIndexCode().substring(0, 2)) && e.getIndexCode().length() > entity.getIndexCode().length() && e.getMfz() != 0.0).collect(Collectors.toList());//满分值不为空的
                for (IndicatorDataEntity mfEntity : mfIndicatorList) {
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(mfEntity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(mfEntity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(mfEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(mfEntity.getDx());
                    otherIndicatorOverviewDto.setIds(mfEntity.getIds());
                    otherIndicatorOverviewDto.setFullValue(BigDecimal.valueOf(mfEntity.getMfz()));

                    String mfFormula = mfEntity.getCalculationFormulaId();
                    String mfIndexValue = Calculator.conversionToSting(mfFormula, mapValue);
                    String mfYoyIndexValue = Calculator.conversionToSting(mfFormula, mapYoyValue);

                    double otherMfz = mfEntity.getMfz();
                    String mfDx = mfEntity.getDx();
                    BigDecimal mfValue = new BigDecimal(mfIndexValue == "-" ? "0" : mfIndexValue);
                    BigDecimal mfYoyValue = new BigDecimal(mfYoyIndexValue == "-" ? "0" : mfYoyIndexValue);
                    BigDecimal otherMfzValue = BigDecimal.valueOf(otherMfz);

                    if ("0".equals(mfDx) || "1".equals(mfDx)) {
                        if (mfValue.compareTo(otherMfzValue) >= 0) {
                            //该指标为满分指标
                            mfFullList.add(mfEntity);
                            tempOtherFull.add(otherIndicatorOverviewDto);
                        } else {
                            //该指标为非满分指标，在这里只统计退步
                            if (mfValue.compareTo(mfYoyValue) <= 0) {
                                tempOtherDown.add(otherIndicatorOverviewDto);
                            }

                        }
                    } else {
                        if (mfValue.compareTo(otherMfzValue) <= 0) {
                            //该指标为满分指标
                            mfFullList.add(mfEntity);
                            tempOtherFull.add(otherIndicatorOverviewDto);
                        } else {
                            //该指标为非满分指标，在这里只统计退步
                            if (mfValue.compareTo(mfYoyValue) >= 0) {
                                tempOtherDown.add(otherIndicatorOverviewDto);
                            }
                        }
                    }
                }
                range = (double) mfFullList.size() / mfIndicatorList.size();
                //指标10、45
                if (range >= 0.6) {
                    fullList.add(indicatorOverviewDto);
                    otherFull.addAll(tempOtherFull);
                } else {
                    downList.add(indicatorOverviewDto);
                    otherDown.addAll(tempOtherDown);
                }
                continue;
            }

            //计算特殊指标13
            if (validIndexCodes2.contains(entity.getIndexCode())) {
                List<IndicatorDataEntity> mfIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().startsWith(entity.getIndexCode().substring(0, 2)) && e.getIndexCode().length() > entity.getIndexCode().length() && e.getMfz() != 0.0).collect(Collectors.toList());//满分值不为空的
                //用来临时存储指标13 满分或者退步的子指标
                List<IndicatorOverviewDto> tempOtherFull = new ArrayList<>();
                List<IndicatorOverviewDto> tempOtherDown = new ArrayList<>();
                for (IndicatorDataEntity mfEntity : mfIndicatorList) {
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(mfEntity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(mfEntity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(mfEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(mfEntity.getIds());
                    otherIndicatorOverviewDto.setFullValue(BigDecimal.valueOf(mfEntity.getMfz()));

                    String mfFormula = mfEntity.getCalculationFormulaId();
                    String mfIndexValue = Calculator.conversionToSting(mfFormula, mapValue);


                    BigDecimal mfValue = new BigDecimal(mfIndexValue == "-" ? "0" : mfIndexValue);
                    if (mfValue.compareTo(new BigDecimal("0.98")) < 0) {
                        flag = false;
                        tempOtherDown.add(otherIndicatorOverviewDto);
                    } else {
                        tempOtherFull.add(otherIndicatorOverviewDto);
                    }
                }
                //指标13
                if (flag) {
                    fullList.add(indicatorOverviewDto);
                    otherFull.addAll(tempOtherFull);
                } else {
                    downList.add(indicatorOverviewDto);
                    otherDown.addAll(tempOtherDown);
                }
                continue;
            }

            //计算特殊指标37、38、39、40、41、这几个指标本身有值，但是计算涉及到了去年的数据导致公式没法配置，所以单拎出来
            if (validIndexCodes3.contains(entity.getIndexCode())) {
                List<IndicatorDataEntity> mfIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().startsWith(entity.getIndexCode().substring(0, 2)) && e.getIndexCode().length() > entity.getIndexCode().length()).collect(Collectors.toList());
                Optional<IndicatorDataEntity> optionaEntity = mfIndicatorList.stream()
                        .filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1.1."))
                        .findFirst();
                if (optionaEntity.isPresent()) {
                    IndicatorDataEntity mfEntity = optionaEntity.get();

                    //拼凑出一个指标  比如指标38. 和 38.1.1，组成一个新的
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();

                    otherIndicatorOverviewDto.setIndicatorName(entity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(entity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(mfEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(mfEntity.getIds());
                    otherIndicatorOverviewDto.setFullValue(mfzValue);

                    String mfFormula = mfEntity.getCalculationFormulaId();
                    String mfIndexValue = Calculator.conversionToSting(mfFormula, mapValue);//今年
                    String mfYoyValue = Calculator.conversionToSting(mfFormula, mapYoyValue);//去年
                    String indicatorValue = calculateGrowthRate(mfIndexValue, mfYoyValue);
                    value = new BigDecimal(indicatorValue.equals("-") ? "0" : indicatorValue);

                    //判断是否获得满分
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  指标值越大越好（大于满分值才能算获得满分）
                        if (value.compareTo(mfzValue) >= 0) {
                            //该指标为满分指标
                            fullList.add(indicatorOverviewDto);
                            otherFull.add(otherIndicatorOverviewDto);
                        } else {
                            downList.add(indicatorOverviewDto);
                            otherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(mfzValue) <= 0) {
                            //该指标为满分指标
                            fullList.add(indicatorOverviewDto);
                            otherFull.add(otherIndicatorOverviewDto);
                        } else {
                            downList.add(indicatorOverviewDto);
                            otherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    }

                }
            }

            //计算特殊指标48
            if (validIndexCodes4.contains(entity.getIndexCode())) {
                List<IndicatorDataEntity> mfIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().startsWith(entity.getIndexCode().substring(0, 2)) && e.getIndexCode().length() > entity.getIndexCode().length()).collect(Collectors.toList());
                Optional<IndicatorDataEntity> optionaEntity = mfIndicatorList.stream()
                        .filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1."))
                        .findFirst();
                if (optionaEntity.isPresent()) {
                    IndicatorDataEntity mfEntity = optionaEntity.get();

                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(entity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(entity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(mfEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(mfEntity.getIds());
                    otherIndicatorOverviewDto.setFullValue(BigDecimal.valueOf(mfEntity.getMfz()));


                    String mfFormula = mfEntity.getCalculationFormulaId();
                    String mfIndexValue = Calculator.conversionToSting(mfFormula, mapValue);//今年
                    String mfYoyValue = Calculator.conversionToSting(mfFormula, mapYoyValue);//去年
                    value = new BigDecimal(mfIndexValue.equals("-") ? "0" : mfIndexValue);
                    yoyValue = new BigDecimal(mfYoyValue == "-" ? "0" : mfYoyValue);

                    //判断是否获得满分
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  指标值越大越好（大于满分值才能算获得满分）
                        if (value.compareTo(mfzValue) >= 0) {
                            //该指标为满分指标
                            fullList.add(indicatorOverviewDto);
                            otherFull.add(otherIndicatorOverviewDto);
                        } else {
                            //该指标为非满分指标，非满分指标分为进步指标和退步指标，根据今年指标值和同比指标值比较即可
                            if (value.compareTo(yoyValue) > 0) {
                                upList.add(indicatorOverviewDto);
                                otherUp.add(otherIndicatorOverviewDto);
                            } else {
                                downList.add(indicatorOverviewDto);
                                // 只统计进步指标
                                otherDown.add(otherIndicatorOverviewDto);
                            }
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(mfzValue) <= 0) {
                            //该指标为满分指标
                            fullList.add(indicatorOverviewDto);
                            otherFull.add(otherIndicatorOverviewDto);
                        } else {
                            //该指标为非满分指标，非满分指标分为进步指标和退步指标
                            if (value.compareTo(yoyValue) < 0) {
                                upList.add(indicatorOverviewDto);
                                otherUp.add(otherIndicatorOverviewDto);
                            } else {
                                downList.add(indicatorOverviewDto);
                                otherDown.add(otherIndicatorOverviewDto);
                            }
                        }
                        continue;
                    }


                }
            }
            //判断是否获得满分
            if ("0".equals(dx) || "1".equals(dx)) {
                //说明是上升指标  指标值越大越好（大于满分值才能算获得满分）
                if (value.compareTo(mfzValue) >= 0) {
                    //该指标为满分指标
                    fullList.add(indicatorOverviewDto);
                } else {
                    //该指标为非满分指标，非满分指标分为进步指标和退步指标，根据今年指标值和同比指标值比较即可
                    if (value.compareTo(yoyValue) > 0) {
                        upList.add(indicatorOverviewDto);
                    } else {
                        downList.add(indicatorOverviewDto);
                    }
                }
            } else if ("2".equals(dx)) {
                //说明是下降指标(指标导向为 2)  指标值越小越好（小于满分值才能算获得满分）
                if (value.compareTo(mfzValue) <= 0) {
                    //该指标为满分指标
                    fullList.add(indicatorOverviewDto);
                } else {
                    //该指标为非满分指标，非满分指标分为进步指标和退步指标
                    if (value.compareTo(yoyValue) < 0) {
                        upList.add(indicatorOverviewDto);
                    } else {
                        downList.add(indicatorOverviewDto);
                    }
                }
            }
        }
        result.put("full", fullList);
        result.put("up", upList);
        result.put("down", downList);

        result.put("otherFull", otherFull);
        result.put("otherDown", otherDown);
        result.put("otherUp", otherUp);
        return result;
    }


    /**
     * 获取监测指标下的科室情况  包括进步、退步、持平的科室
     *
     * @param indicatorCalculateDto
     * @return
     */
    public List<DataListDto> getMonitorIndicatorDataList(IndicatorCalculateDto indicatorCalculateDto) {
        List<DataListDto> dataListDtoList = new ArrayList<>();
        List<String> times = indicatorCalculateDto.getTimes();
        if (times.size() == 0) {
            return null;
        }
        List<String> yoyTimes = getYoyTime(times);
        List<String> beforeYoyTimes = getYoyTime(yoyTimes);
        List<String> previousYoyTimes = getYoyTime(beforeYoyTimes);
        List<String> lastEndYoyTimes = getYoyTime(previousYoyTimes);

        indicatorCalculateDto.setStartTime(times.get(0));
        indicatorCalculateDto.setEndTime(times.get(times.size() - 1));
        //查指标 key  按照满分 ，进不退步之类的指标分类
        Map<String, List<IndicatorOverviewDto>> overviewData = getMonitorIndicatorOverviewData(indicatorCalculateDto);
        //flag   0:满分  1:进步  其它:退步
        String key = indicatorCalculateDto.getFlag() == 0 ? "full" : indicatorCalculateDto.getFlag() == 1 ? "up" : "down";
        if (CollectionUtils.isEmpty(overviewData.get(key))) {
            return null;
        }
        // 查出所有手填指标的 id
        List<ElementDataEntity> elementDataEntities = indicatorCalculateMapper.getDeptElement();
        //将id全部抽取出来
        List<String> handFillIds = elementDataEntities.stream().map(e -> e.getId()).collect(Collectors.toList());

        List<IndicatorOverviewDto> deptIndicatorList = new ArrayList<>();
        // 确定当前指标是否是科室层面的指标  只有科室层面的指标才有必要查科室数据
        List<IndicatorOverviewDto> indicatorOverviewDtos = overviewData.get(key);
        List<IndicatorOverviewDto> otherIndicatorOverviewDtos = new ArrayList<>();

        if (key.equals("full")) {
            otherIndicatorOverviewDtos = overviewData.get("otherFull");
        }

        if (key.equals("up")) {
            otherIndicatorOverviewDtos = overviewData.get("otherUp");
        }

        if (key.equals("down")) {
            otherIndicatorOverviewDtos = overviewData.get("otherDown");
        }
        List<IndicatorOverviewDto> allIndicatorOverviewDtos = new ArrayList<>();
        allIndicatorOverviewDtos.addAll(indicatorOverviewDtos);
        allIndicatorOverviewDtos.addAll(otherIndicatorOverviewDtos);

        for (IndicatorOverviewDto indicatorOverviewDto : allIndicatorOverviewDtos) {
            if (org.springframework.util.StringUtils.isEmpty(indicatorOverviewDto.getIds())) {
                continue;
            }
            String[] ids = indicatorOverviewDto.getIds().split(",");
            List<String> idList = Arrays.asList(ids);
            if (handFillIds.containsAll(idList)) {
                //说明是科室指标
                deptIndicatorList.add(indicatorOverviewDto);
            }
        }

        //查询47个科室  把所有天表这一时间段的科室数据进行累加，然后再根据科室去筛选
        List<DepartmentDto> departmentDtoList = indicatorCalculateMapper.getDepartments();
        indicatorCalculateDto.setDepartmentDtoList(departmentDtoList);


        indicatorCalculateDto.setStartTime(times.get(0));
        indicatorCalculateDto.setEndTime(times.get(times.size() - 1));
        List<DepartmentIndicatorEntity> curDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(yoyTimes.get(0));
        indicatorCalculateDto.setEndTime(yoyTimes.get(yoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> lastDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(beforeYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(beforeYoyTimes.get(beforeYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> beforeDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(previousYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(previousYoyTimes.get(previousYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> previousDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(lastEndYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(lastEndYoyTimes.get(lastEndYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> lastEndDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        //根据科室进行分组
        Map<String, List<DepartmentIndicatorEntity>> curMapValue = curDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> lastMapValue = lastDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> beforeMapValue = beforeDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> previousMapValue = previousDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> lastEndMapValue = lastEndDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));

        //特殊指标类型
        Set<String> validIndexCodes3 = new HashSet<>(Arrays.asList("38.", "39.", "40.", "41."));

        //计算科室指标下的进步、退步、持平科室 dataListDtoList
        for (IndicatorOverviewDto indicatorOverviewDto : deptIndicatorList) {

            DataListDto dataListDto = new DataListDto();
            DataDetail dataDetail = new DataDetail();
            dataListDto.setIndicatorName(indicatorOverviewDto.getIndicatorName());
            dataListDto.setDataDetails(dataDetail);

            String formula = indicatorOverviewDto.getCalculationFormulaId();
            String dx = indicatorOverviewDto.getDx();//指标导向
            BigDecimal fullValue = indicatorOverviewDto.getFullValue();
            for (DepartmentDto departmentDto : departmentDtoList) {

                AnnexDataDto annexDataDto = new AnnexDataDto();
                annexDataDto.setDeptName(departmentDto.getDepartmentName());

                List<AnnexYearDto> annexYearDtoList = new ArrayList<>();
                AnnexYearDto curAnnexYearDto = new AnnexYearDto();
                AnnexYearDto lastAnnexYearDto = new AnnexYearDto();
                AnnexYearDto beforeAnnexYearDto = new AnnexYearDto();
                annexYearDtoList.add(curAnnexYearDto);
                annexYearDtoList.add(lastAnnexYearDto);
                annexYearDtoList.add(beforeAnnexYearDto);
                annexDataDto.setAnnexYearDtos(annexYearDtoList);

                curAnnexYearDto.setTime(times.get(0) + "~" + times.get(times.size() - 1));
                lastAnnexYearDto.setTime(yoyTimes.get(0) + "~" + yoyTimes.get(yoyTimes.size() - 1));
                beforeAnnexYearDto.setTime(beforeYoyTimes.get(0) + "~" + beforeYoyTimes.get(beforeYoyTimes.size() - 1));

                curAnnexYearDto.setFullValue(fullValue);
                lastAnnexYearDto.setFullValue(fullValue);
                beforeAnnexYearDto.setFullValue(fullValue);

                List<DepartmentIndicatorEntity> curList = curMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> lastList = lastMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> beforeList = beforeMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> previousList = previousMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> lastEndList = lastEndMapValue.get(departmentDto.getDepartmentName());

                String indexValue = "0";
                String lastYoyValue = "0";
                String beforeYoyValue = "0";
                String previousYoyValue = "0";
                String lastEndYoyValue = "0";
                //解析当前指标的公式，通过元素值计算指标值
                if (curList != null) {
                    Map<String, String> mapValue = curList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    indexValue = Calculator.conversionToSting(formula, mapValue);//当前指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (indexValue.equals("-")) {
                        indexValue = "0";
                    }
                }
                if (lastList != null) {
                    Map<String, String> mapLastValue = lastList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    lastYoyValue = Calculator.conversionToSting(formula, mapLastValue);//去年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (lastYoyValue.equals("-")) {
                        lastYoyValue = "0";
                    }
                }

                if (beforeList != null) {
                    Map<String, String> mapBeforeValue = beforeList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    beforeYoyValue = Calculator.conversionToSting(formula, mapBeforeValue);//去年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (beforeYoyValue.equals("-")) {
                        beforeYoyValue = "0";
                    }
                }
                if (previousList != null) {
                    Map<String, String> mapPreviousValue = previousList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    previousYoyValue = Calculator.conversionToSting(formula, mapPreviousValue);//前年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (previousYoyValue.equals("-")) {
                        previousYoyValue = "0";
                    }
                }
                if (lastEndList != null) {
                    Map<String, String> mapLastEndValue = lastEndList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    lastEndYoyValue = Calculator.conversionToSting(formula, mapLastEndValue);//前年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (lastEndYoyValue.equals("-")) {
                        lastEndYoyValue = "0";
                    }
                }
                // 比较今年、去年、前年时期的值，得出进步、退步、持平的科室
                BigDecimal indexDecimal = new BigDecimal(indexValue);
                BigDecimal lastDecimal = new BigDecimal(lastYoyValue);
                BigDecimal beforeDecimal = new BigDecimal(beforeYoyValue);
                BigDecimal previousDecimal = new BigDecimal(previousYoyValue);//大前年
                BigDecimal lastEndDecimal = new BigDecimal(lastEndYoyValue);//大大前年

                curAnnexYearDto.setIndicatorValue(indexDecimal);
                lastAnnexYearDto.setIndicatorValue(lastDecimal);
                beforeAnnexYearDto.setIndicatorValue(beforeDecimal);

                //计算同比增幅
                String yoyValue = calculateGrowthRate(indexValue, lastYoyValue);
                String lastValue = calculateGrowthRate(lastYoyValue, beforeYoyValue);
                String beforeValue = calculateGrowthRate(beforeYoyValue, previousYoyValue);


                curAnnexYearDto.setYoyValue(new BigDecimal(yoyValue));
                lastAnnexYearDto.setYoyValue(new BigDecimal(lastValue));
                beforeAnnexYearDto.setYoyValue(new BigDecimal(beforeValue));

                if (validIndexCodes3.contains(indicatorOverviewDto.getIndexCode())) {
                    BigDecimal tempYoyValue = new BigDecimal(yoyValue);
                    BigDecimal tempLastValue = new BigDecimal(lastValue);

                    curAnnexYearDto.setIndicatorValue(tempYoyValue);
                    lastAnnexYearDto.setIndicatorValue(tempLastValue);
                    beforeAnnexYearDto.setIndicatorValue(new BigDecimal(beforeValue));

                    indexDecimal = tempYoyValue;
                    lastDecimal = tempLastValue;

                    String otherYoyValue = calculateGrowthRate(yoyValue, lastValue);
                    String otherLastValue = calculateGrowthRate(lastValue, beforeValue);

                    String lastEndValue = calculateGrowthRate(previousYoyValue, lastEndYoyValue);
                    String otherBeforeValue = calculateGrowthRate(beforeValue, lastEndValue);

                    curAnnexYearDto.setYoyValue(new BigDecimal(otherYoyValue));
                    lastAnnexYearDto.setYoyValue(new BigDecimal(otherLastValue));
                    beforeAnnexYearDto.setYoyValue(new BigDecimal(otherBeforeValue));

                }


                //判断科室类型：临床非手术和临床手术 0：非手术科室   1：手术科室
                Integer type = departmentDto.getType();
                //分为两个大类  满分和非满分，非满分包含： 进步 退步 持平
                //判断是否获得满分
                if ("0".equals(dx) || "1".equals(dx)) {
                    //说明是上升指标  指标值越大越好（大于满分值才能算获得满分）
                    if (indexDecimal.compareTo(fullValue) >= 0) {
                        //该科室为满分科室
                        if (type == 0) {
                            //满分非手术
                            dataDetail.getTableList8().add(annexDataDto);
                        } else {
                            //满分手术
                            dataDetail.getTableList7().add(annexDataDto);
                        }
                    } else {
                        //该科室为非满分科室，非满分科室分为进步科室和退步科室以及持平科室，根据今年指标值和同比指标值比较即可
                        if (indexDecimal.compareTo(lastDecimal) > 0) {
                            if (type == 0) {
                                //进步非手术科室
                                dataDetail.getTableList6().add(annexDataDto);
                            } else {
                                //进步手术科室
                                dataDetail.getTableList5().add(annexDataDto);
                            }
                        } else if (indexDecimal.compareTo(lastDecimal) == 0) {
                            if (type == 0) {
                                //持平非手术科室
                                dataDetail.getTableList4().add(annexDataDto);
                            } else {
                                //持平手术科室
                                dataDetail.getTableList3().add(annexDataDto);
                            }
                        } else {
                            if (type == 0) {
                                //退步非手术科室
                                dataDetail.getTableList2().add(annexDataDto);
                            } else {
                                //退步手术科室
                                dataDetail.getTableList1().add(annexDataDto);
                            }
                        }
                    }
                } else if ("2".equals(dx)) {
                    //说明是下降指标(指标导向为 2)  指标值越小越好（小于满分值才能算获得满分）
                    if (indexDecimal.compareTo(fullValue) <= 0) {
                        //该科室为满分科室
                        if (type == 0) {
                            //满分非手术
                            dataDetail.getTableList8().add(annexDataDto);
                        } else {
                            //满分手术
                            dataDetail.getTableList7().add(annexDataDto);
                        }
                    } else {
                        //该科室为非满分科室，非满分科室分为进步科室和退步科室，根据今年指标值和同比指标值比较即可
                        if (indexDecimal.compareTo(lastDecimal) < 0) {
                            if (type == 0) {
                                //进步非手术科室
                                dataDetail.getTableList5().add(annexDataDto);
                            } else {
                                //进步手术科室
                                dataDetail.getTableList6().add(annexDataDto);
                            }
                        } else if (indexDecimal.compareTo(lastDecimal) == 0) {
                            if (type == 0) {
                                //持平非手术科室
                                dataDetail.getTableList4().add(annexDataDto);
                            } else {
                                //持平手术科室
                                dataDetail.getTableList3().add(annexDataDto);
                            }
                        } else {
                            if (type == 0) {
                                //退步非手术科室
                                dataDetail.getTableList2().add(annexDataDto);
                            } else {
                                //退步手术科室
                                dataDetail.getTableList1().add(annexDataDto);
                            }
                        }
                    }
                }
            }
            dataListDtoList.add(dataListDto);
        }
        return dataListDtoList;
    }


    /**
     * 非监测指标整体情况
     * 非监测指标没有满分值
     *
     * @param indicatorCalculateDto
     * @return
     */
    public Map<String, List<IndicatorOverviewDto>> getCommonIndicatorOverviewData(IndicatorCalculateDto indicatorCalculateDto) {
        //获取非监测指标集合
        List<IndicatorDataEntity> unKeyIndicatorList = indicatorCalculateMapper.getUnKeyIndicator(indicatorCalculateDto);
        List<IndicatorDataEntity> otherIndicatorList = indicatorCalculateMapper.getOtherCommonIndicator(indicatorCalculateDto);

        List<IndicatorDataEntity> allIndicatorList = new ArrayList<>();
        allIndicatorList.addAll(unKeyIndicatorList);
        allIndicatorList.addAll(otherIndicatorList);


        List<String> times = indicatorCalculateDto.getTimes();
        List<String> yoyTimes = getYoyTime(times);//获取同比时间集合

        //对所有涉及到的id进行去重
        List<String> elementIds = gatherCommonService.getAllElementIds(allIndicatorList);
        //查询元素定义表，确定元素数据来源 天表、月表、手填表等
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> dayTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "1".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> monthTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "2".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> handTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "3".equals(s.getDataTable())).collect(Collectors.toList());

        List<DepartmentIndicatorEntity> departmentIndicatorEntityList = new ArrayList<>();// 存放当前时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityYoyList = new ArrayList<>();// 存放同比时间的所有的天表、月表、手填表数据

        //查出天表数据 求的是指定时间区间的 天表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(dayTable)) {
            indicatorCalculateDto.setElementIds(dayTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            int size = indicatorCalculateDto.getTimes().size();
            indicatorCalculateDto.setStartTime(indicatorCalculateDto.getTimes().get(0));
            indicatorCalculateDto.setEndTime(indicatorCalculateDto.getTimes().get(size - 1));
            List<DepartmentIndicatorEntity> dayData = indicatorCalculateMapper.queryEscalationGroupByDay(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityList.addAll(dayData);

            size = yoyTimes.size();
            indicatorCalculateDto.setStartTime(yoyTimes.get(0));
            indicatorCalculateDto.setEndTime(yoyTimes.get(size - 1));
            List<DepartmentIndicatorEntity> dayYoyData = indicatorCalculateMapper.queryEscalationGroupByDay(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityYoyList.addAll(dayYoyData);
        }


        List<String> groupTimes;
        //查出月表数据 求的是指定时间区间的 月表数据之和（月表每个月数据就一条 求和与不求和没有区别）
        if (!org.springframework.util.CollectionUtils.isEmpty(monthTable)) {

            indicatorCalculateDto.setElementIds(monthTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            groupTimes = times.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            List<DepartmentIndicatorEntity> monthData = indicatorCalculateMapper.queryEscalationNew(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityList.addAll(monthData);

            groupTimes = yoyTimes.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            List<DepartmentIndicatorEntity> monthYoyData = indicatorCalculateMapper.queryEscalationNew(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityYoyList.addAll(monthYoyData);

        }

        //查出手填表数据 求的是指定时间区间的 手填表数据之和（手填表每个月数据就一条 求和与不求和没有区别）
        if (!org.springframework.util.CollectionUtils.isEmpty(handTable)) {
            indicatorCalculateDto.setElementIds(handTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            //手填表数据只需要时间精确到月
            groupTimes = times.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            // 查找taskId  部门的话精确到每个部门的每个月的每一条
            List<String> taskIds = reportTaskMapper.selectReportTasks(groupTimes, indicatorCalculateDto.getUserInfo().getWardName(), indicatorCalculateDto.getUserInfo().getParentDepartmentId());
            List<DepartmentIndicatorEntity> handTableData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableData = reportMapper.queryAnalysisReport(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityList.addAll(handTableData);


            groupTimes = yoyTimes.stream().map(time -> time.substring(0, 7)).distinct().collect(Collectors.toList());
            indicatorCalculateDto.setGroupTimes(groupTimes);
            taskIds = reportTaskMapper.selectReportTasks(groupTimes, indicatorCalculateDto.getUserInfo().getWardName(), indicatorCalculateDto.getUserInfo().getParentDepartmentId());
            List<DepartmentIndicatorEntity> handTableYoyData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableYoyData = reportMapper.queryAnalysisReport(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityYoyList.addAll(handTableYoyData);
        }


        Map<String, String> mapValue = new HashMap<>();
        Map<String, String> mapYoyValue = new HashMap<>();
        mapValue = departmentIndicatorEntityList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapYoyValue = departmentIndicatorEntityYoyList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));

        Map<String, List<IndicatorOverviewDto>> result = new HashMap<>();
        List<IndicatorOverviewDto> downList = new ArrayList<>();
        List<IndicatorOverviewDto> upList = new ArrayList<>();

        //用来存储特殊指标 进步或者退步的子指标
        List<IndicatorOverviewDto> otherUp = new ArrayList<>();
        List<IndicatorOverviewDto> otherDown = new ArrayList<>();

        double range = 0.0;
        boolean flag = true;
        Set<String> validIndexCodes1 = new HashSet<>(Arrays.asList("7.", "16.", "20.", "21.", "28."));
        Set<String> validIndexCodes2 = new HashSet<>(Arrays.asList("37."));
        Set<String> validIndexCodes3 = new HashSet<>(Arrays.asList("47."));
        Set<String> validIndexCodes4 = new HashSet<>(Arrays.asList("49"));

        for (IndicatorDataEntity entity : unKeyIndicatorList) {

            //解析当前指标的公式，通过元素值计算指标值
            String formula = entity.getCalculationFormulaId();
            String indexValue = Calculator.conversionToSting(formula, mapValue);//当前指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
            String indexYoyValue = Calculator.conversionToSting(formula, mapYoyValue);//同期指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值

            String dx = entity.getDx();
            BigDecimal value = new BigDecimal(indexValue == "-" ? "0" : indexValue);
            BigDecimal yoyValue = new BigDecimal(indexYoyValue == "-" ? "0" : indexYoyValue);

            String ratio = calculateGrowthRate(indexValue, indexYoyValue);
            ratio = ratio.equals("-") ? "0" : ratio;


            IndicatorOverviewDto indicatorOverviewDto = new IndicatorOverviewDto();
            indicatorOverviewDto.setIndicatorXh(Integer.valueOf(entity.getId()));
            indicatorOverviewDto.setIndexCode(entity.getIndexCode());
            indicatorOverviewDto.setIndicatorName(entity.getIndexName());
            indicatorOverviewDto.setUnit(entity.getIndexUnit());
            indicatorOverviewDto.setTime(times.get(0) + "~" + times.get(times.size() - 1));
            indicatorOverviewDto.setIndicatorValue(value);
            indicatorOverviewDto.setYoyValue(new BigDecimal(ratio));
            indicatorOverviewDto.setResponsibleDepartment(entity.getZrbm());
            indicatorOverviewDto.setLeader(entity.getFgld());
            indicatorOverviewDto.setIds(entity.getIds());
            indicatorOverviewDto.setCalculationFormulaId(entity.getCalculationFormulaId());
            indicatorOverviewDto.setDx(entity.getDx());


            //计算特殊指标7 16 20 21 28 这些指标涉及到的子指标只有两个 两个都进步父指标就算进步，有一个退步父指标就算退步
            if (validIndexCodes1.contains(entity.getIndexCode())) {
                List<IndicatorDataEntity> commonIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1.") || e.getIndexCode().equals(entity.getIndexCode() + "2.")).collect(Collectors.toList());
                List<IndicatorOverviewDto> tempOtherUp = new ArrayList<>();
                List<IndicatorOverviewDto> tempOtherDown = new ArrayList<>();
                for (IndicatorDataEntity commonEntity : commonIndicatorList) {
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(commonEntity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(commonEntity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(commonEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(commonEntity.getIds());

                    String commonFormula = commonEntity.getCalculationFormulaId();
                    String commonIndexValue = Calculator.conversionToSting(commonFormula, mapValue);
                    String commonYoyValue = Calculator.conversionToSting(commonFormula, mapYoyValue);


                    BigDecimal indexBigDecimal = new BigDecimal(commonIndexValue == "-" ? "0" : commonIndexValue);//今年指标值
                    BigDecimal yoyindexBigDecimal = new BigDecimal(commonYoyValue == "-" ? "0" : commonYoyValue);//同期指标值


                    //判断是否进步
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  指标值越大越好
                        if (indexBigDecimal.compareTo(yoyindexBigDecimal) > 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            flag = false;
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(new BigDecimal("0")) < 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            flag = false;
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    }
                }
                if (flag) {
                    upList.add(indicatorOverviewDto);
                    otherUp.addAll(tempOtherUp);
                } else {
                    downList.add(indicatorOverviewDto);
                    otherDown.addAll(tempOtherDown);
                }
                continue;
            }

            //计算特殊指标37  这个指标本身有值，但是计算涉及到了去年的数据导致公式没法配置，所以单拎出来
            if (validIndexCodes2.contains(entity.getIndexCode())) {
                List<IndicatorDataEntity> commonIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1.1.")).collect(Collectors.toList());
                for (IndicatorDataEntity commonEntity : commonIndicatorList) {

                    //拼凑出一个指标  比如指标37. 和 37.1.1，组成一个新的
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();

                    otherIndicatorOverviewDto.setIndicatorName(entity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(entity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(commonEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(commonEntity.getIds());

                    String commonFormula = commonEntity.getCalculationFormulaId();
                    String commonIndexValue = Calculator.conversionToSting(commonFormula, mapValue);//今年
                    String commonYoyValue = Calculator.conversionToSting(commonFormula, mapYoyValue);//去年
                    String indicatorValue = calculateGrowthRate(commonIndexValue, commonYoyValue);
                    value = new BigDecimal(indicatorValue.equals("-") ? "0" : indicatorValue);

                    //判断是否进步
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  这个指标是非监测指标，不存在与满分值的对比 要想求出进退步还需要计算前年的值 暂时不求前年的值，将其直接归为进步指标里
                        if (value.compareTo(new BigDecimal("0")) >= 0) {
                            upList.add(indicatorOverviewDto);
                            otherUp.add(otherIndicatorOverviewDto);
                        } else {
                            downList.add(indicatorOverviewDto);
                            otherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(new BigDecimal("0")) <= 0) {
                            upList.add(indicatorOverviewDto);
                            otherUp.add(otherIndicatorOverviewDto);
                        } else {
                            downList.add(indicatorOverviewDto);
                            otherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    }
                }
                continue;
            }


            //计算特殊指标47
            if (validIndexCodes3.contains(entity.getIndexCode())) {
                List<IndicatorOverviewDto> tempOtherUp = new ArrayList<>();
                List<IndicatorOverviewDto> tempOtherDown = new ArrayList<>();
                //计算特殊指标使用
                List<IndicatorDataEntity> commonIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1.") || e.getIndexCode().equals(entity.getIndexCode() + "2.") || e.getIndexCode().equals(entity.getIndexCode() + "3.")).collect(Collectors.toList());
                for (IndicatorDataEntity commonEntity : commonIndicatorList) {
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(commonEntity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(commonEntity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(commonEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(commonEntity.getIds());

                    String commonFormula = commonEntity.getCalculationFormulaId();
                    String commonIndexValue = Calculator.conversionToSting(commonFormula, mapValue);
                    String commonYoyValue = Calculator.conversionToSting(commonFormula, mapYoyValue);


                    BigDecimal indexBigDecimal = new BigDecimal(commonIndexValue == "-" ? "0" : commonIndexValue);//今年指标值
                    BigDecimal yoyindexBigDecimal = new BigDecimal(commonYoyValue == "-" ? "0" : commonYoyValue);//同期指标值

                    //判断是否进步
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  指标值越大越好
                        if (indexBigDecimal.compareTo(yoyindexBigDecimal) > 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(new BigDecimal("0")) < 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    }


                }
                range = (double) tempOtherUp.size() / commonIndicatorList.size();

                if (range >= 0.6) {
                    upList.add(indicatorOverviewDto);
                    otherUp.addAll(tempOtherUp);
                } else {
                    downList.add(indicatorOverviewDto);
                    otherDown.addAll(tempOtherDown);
                }
                continue;
            }

            //计算特殊指标49
            if (validIndexCodes4.contains(entity.getIndexCode())) {
                List<IndicatorOverviewDto> tempOtherUp = new ArrayList<>();
                List<IndicatorOverviewDto> tempOtherDown = new ArrayList<>();
                //计算特殊指标使用
                List<IndicatorDataEntity> commonIndicatorList = otherIndicatorList.stream().filter(e -> e.getIndexCode().equals(entity.getIndexCode() + "1.") || e.getIndexCode().equals(entity.getIndexCode() + "2.") || e.getIndexCode().equals(entity.getIndexCode() + "3.") || e.getIndexCode().equals(entity.getIndexCode() + "4.")).collect(Collectors.toList());
                for (IndicatorDataEntity commonEntity : commonIndicatorList) {
                    IndicatorOverviewDto otherIndicatorOverviewDto = new IndicatorOverviewDto();
                    otherIndicatorOverviewDto.setIndicatorName(commonEntity.getIndexName());
                    otherIndicatorOverviewDto.setIndexCode(commonEntity.getIndexCode());
                    otherIndicatorOverviewDto.setCalculationFormulaId(commonEntity.getCalculationFormulaId());
                    otherIndicatorOverviewDto.setDx(entity.getDx());
                    otherIndicatorOverviewDto.setIds(commonEntity.getIds());

                    String commonFormula = commonEntity.getCalculationFormulaId();
                    String commonIndexValue = Calculator.conversionToSting(commonFormula, mapValue);
                    String commonYoyValue = Calculator.conversionToSting(commonFormula, mapYoyValue);


                    BigDecimal indexBigDecimal = new BigDecimal(commonIndexValue == "-" ? "0" : commonIndexValue);//今年指标值
                    BigDecimal yoyindexBigDecimal = new BigDecimal(commonYoyValue == "-" ? "0" : commonYoyValue);//同期指标值

                    //判断是否进步
                    if ("0".equals(dx) || "1".equals(dx)) {
                        //说明是上升指标  指标值越大越好
                        if (indexBigDecimal.compareTo(yoyindexBigDecimal) > 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    } else if ("2".equals(dx)) {
                        if (value.compareTo(new BigDecimal("0")) < 0) {
                            tempOtherUp.add(otherIndicatorOverviewDto);
                        } else {
                            tempOtherDown.add(otherIndicatorOverviewDto);
                        }
                        continue;
                    }


                }
                range = (double) tempOtherUp.size() / commonIndicatorList.size();

                if (range >= 0.6) {
                    upList.add(indicatorOverviewDto);
                    otherUp.addAll(tempOtherUp);
                } else {
                    downList.add(indicatorOverviewDto);
                    otherDown.addAll(tempOtherDown);
                }
                continue;
            }


            if ("0".equals(dx) || "1".equals(dx)) {
                //说明是上升指标  指标值越大越好
                if (value.compareTo(yoyValue) > 0) {
                    upList.add(indicatorOverviewDto);
                } else {
                    downList.add(indicatorOverviewDto);
                }

            } else if ("2".equals(dx)) {
                //说明是下降指标(指标导向为 2)  指标值越小越好
                if (value.compareTo(yoyValue) < 0) {
                    upList.add(indicatorOverviewDto);
                } else {
                    downList.add(indicatorOverviewDto);
                }
            }
        }
        result.put("up", upList);
        result.put("down", downList);

        result.put("otherUp", otherUp);
        result.put("otherDown", otherDown);
        return result;
    }

    /**
     * 获取非监测指标下的科室情况  包括进步、退步、持平的科室
     *
     * @param indicatorCalculateDto
     * @return
     */
    public List<DataListDto> getCommonIndicatorDataList(IndicatorCalculateDto indicatorCalculateDto) {
        List<DataListDto> dataListDtoList = new ArrayList<>();
        List<String> times = indicatorCalculateDto.getTimes();
        if (times.size() == 0) {
            return null;
        }
        List<String> yoyTimes = getYoyTime(times);
        List<String> beforeYoyTimes = getYoyTime(yoyTimes);
        List<String> previousYoyTimes = getYoyTime(beforeYoyTimes);
        List<String> lastEndYoyTimes = getYoyTime(previousYoyTimes);

        indicatorCalculateDto.setStartTime(times.get(0));
        indicatorCalculateDto.setEndTime(times.get(times.size() - 1));

        Map<String, List<IndicatorOverviewDto>> overviewData = getCommonIndicatorOverviewData(indicatorCalculateDto);
        //flag   0:满分  1:进步  其它:退步
        String key = indicatorCalculateDto.getFlag() == 0 ? "full" : indicatorCalculateDto.getFlag() == 1 ? "up" : "down";
        if (CollectionUtils.isEmpty(overviewData.get(key))) {
            return null;
        }
        // 查出所有手填指标的 id
        List<ElementDataEntity> elementDataEntities = indicatorCalculateMapper.getDeptElement();
        //将id全部抽取出来
        List<String> handFillIds = elementDataEntities.stream().map(e -> e.getId()).collect(Collectors.toList());

        List<IndicatorOverviewDto> deptIndicatorList = new ArrayList<>();
        List<IndicatorOverviewDto> indicatorOverviewDtos = overviewData.get(key);
        List<IndicatorOverviewDto> otherIndicatorOverviewDtos = new ArrayList<>();


        if (key.equals("up")) {
            otherIndicatorOverviewDtos = overviewData.get("otherUp");
        }

        if (key.equals("down")) {
            otherIndicatorOverviewDtos = overviewData.get("otherDown");
        }
        List<IndicatorOverviewDto> allIndicatorOverviewDtos = new ArrayList<>();
        allIndicatorOverviewDtos.addAll(indicatorOverviewDtos);
        allIndicatorOverviewDtos.addAll(otherIndicatorOverviewDtos);

        for (IndicatorOverviewDto indicatorOverviewDto : allIndicatorOverviewDtos) {
            if (org.springframework.util.StringUtils.isEmpty(indicatorOverviewDto.getIds())) {
                continue;
            }
            String[] ids = indicatorOverviewDto.getIds().split(",");
            List<String> idList = Arrays.asList(ids);
            if (handFillIds.containsAll(idList)) {
                //说明是科室指标
                deptIndicatorList.add(indicatorOverviewDto);
            }
        }

        //查询47个科室  把所有天表这一时间段的科室数据进行累加，然后再根据科室去筛选
        List<DepartmentDto> departmentDtoList = indicatorCalculateMapper.getDepartments();
        indicatorCalculateDto.setDepartmentDtoList(departmentDtoList);


        indicatorCalculateDto.setStartTime(times.get(0));
        indicatorCalculateDto.setEndTime(times.get(times.size() - 1));
        List<DepartmentIndicatorEntity> curDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(yoyTimes.get(0));
        indicatorCalculateDto.setEndTime(yoyTimes.get(yoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> lastDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(beforeYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(beforeYoyTimes.get(beforeYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> beforeDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(previousYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(previousYoyTimes.get(previousYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> previousDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        indicatorCalculateDto.setStartTime(lastEndYoyTimes.get(0));
        indicatorCalculateDto.setEndTime(lastEndYoyTimes.get(lastEndYoyTimes.size() - 1));
        List<DepartmentIndicatorEntity> lastEndDayData = indicatorCalculateMapper.queryEscalationGroupByDept(indicatorCalculateDto); //天表数据

        //根据科室进行分组
        Map<String, List<DepartmentIndicatorEntity>> curMapValue = curDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> lastMapValue = lastDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> beforeMapValue = beforeDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> previousMapValue = previousDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));
        Map<String, List<DepartmentIndicatorEntity>> lastEndMapValue = lastEndDayData.stream().collect(Collectors.groupingBy(e -> e.getDeptName()));

        //特殊指标类型
        Set<String> validIndexCodes3 = new HashSet<>(Arrays.asList("37."));

        //计算科室指标下的进步、退步、持平科室
        for (IndicatorOverviewDto indicatorOverviewDto : deptIndicatorList) {

            DataListDto dataListDto = new DataListDto();
            DataDetail dataDetail = new DataDetail();
            dataListDto.setIndicatorName(indicatorOverviewDto.getIndicatorName());
            dataListDto.setDataDetails(dataDetail);

            String formula = indicatorOverviewDto.getCalculationFormulaId();
            String dx = indicatorOverviewDto.getDx();//指标导向
            BigDecimal fullValue = indicatorOverviewDto.getFullValue();
            for (DepartmentDto departmentDto : departmentDtoList) {

                AnnexDataDto annexDataDto = new AnnexDataDto();
                annexDataDto.setDeptName(departmentDto.getDepartmentName());

                List<AnnexYearDto> annexYearDtoList = new ArrayList<>();
                AnnexYearDto curAnnexYearDto = new AnnexYearDto();
                AnnexYearDto lastAnnexYearDto = new AnnexYearDto();
                AnnexYearDto beforeAnnexYearDto = new AnnexYearDto();
                annexYearDtoList.add(curAnnexYearDto);
                annexYearDtoList.add(lastAnnexYearDto);
                annexYearDtoList.add(beforeAnnexYearDto);
                annexDataDto.setAnnexYearDtos(annexYearDtoList);


                curAnnexYearDto.setTime(times.get(0) + "~" + times.get(times.size() - 1));
                lastAnnexYearDto.setTime(yoyTimes.get(0) + "~" + yoyTimes.get(yoyTimes.size() - 1));
                beforeAnnexYearDto.setTime(beforeYoyTimes.get(0) + "~" + beforeYoyTimes.get(beforeYoyTimes.size() - 1));

                curAnnexYearDto.setFullValue(fullValue);
                lastAnnexYearDto.setFullValue(fullValue);
                beforeAnnexYearDto.setFullValue(fullValue);

                List<DepartmentIndicatorEntity> curList = curMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> lastList = lastMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> beforeList = beforeMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> previousList = previousMapValue.get(departmentDto.getDepartmentName());
                List<DepartmentIndicatorEntity> lastEndList = lastEndMapValue.get(departmentDto.getDepartmentName());

                String indexValue = "0";
                String lastYoyValue = "0";
                String beforeYoyValue = "0";
                String previousYoyValue = "0";
                String lastEndYoyValue = "0";
                //解析当前指标的公式，通过元素值计算指标值
                if (curList != null) {
                    Map<String, String> mapValue = curList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    indexValue = Calculator.conversionToSting(formula, mapValue);//当前指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (indexValue.equals("-")) {
                        indexValue = "0";
                    }
                }
                if (lastList != null) {
                    Map<String, String> mapLastValue = lastList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    lastYoyValue = Calculator.conversionToSting(formula, mapLastValue);//去年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (lastYoyValue.equals("-")) {
                        lastYoyValue = "0";
                    }
                }

                if (beforeList != null) {
                    Map<String, String> mapBeforeValue = beforeList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    beforeYoyValue = Calculator.conversionToSting(formula, mapBeforeValue);//去年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (beforeYoyValue.equals("-")) {
                        beforeYoyValue = "0";
                    }
                }
                if (previousList != null) {
                    Map<String, String> mapPreviousValue = previousList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    previousYoyValue = Calculator.conversionToSting(formula, mapPreviousValue);//前年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (previousYoyValue.equals("-")) {
                        previousYoyValue = "0";
                    }
                }
                if (lastEndList != null) {
                    Map<String, String> mapLastEndValue = lastEndList.stream().collect(Collectors.toMap(e -> "${" + e.getId() + "}", e -> e.getElementNumber()));
                    lastEndYoyValue = Calculator.conversionToSting(formula, mapLastEndValue);//前年指标值,如果当前指标涉及到多个元素计算，那么结果就是多元素数据计算的值，如果不涉及，就是其本身的值
                    if (lastEndYoyValue.equals("-")) {
                        lastEndYoyValue = "0";
                    }
                }
                // 比较今年、去年、前年时期的值，得出进步、退步、持平的科室
                BigDecimal indexDecimal = new BigDecimal(indexValue);
                BigDecimal lastDecimal = new BigDecimal(lastYoyValue);
                BigDecimal beforeDecimal = new BigDecimal(beforeYoyValue);
                BigDecimal previousDecimal = new BigDecimal(previousYoyValue);//大前年
                BigDecimal lastEndDecimal = new BigDecimal(lastEndYoyValue);//大大前年

                curAnnexYearDto.setIndicatorValue(indexDecimal);
                lastAnnexYearDto.setIndicatorValue(lastDecimal);
                beforeAnnexYearDto.setIndicatorValue(beforeDecimal);

                //计算同比增幅
                String yoyValue = calculateGrowthRate(indexValue, lastYoyValue);
                String lastValue = calculateGrowthRate(lastYoyValue, beforeYoyValue);
                String beforeValue = calculateGrowthRate(beforeYoyValue, previousYoyValue);


                curAnnexYearDto.setYoyValue(new BigDecimal(yoyValue));
                lastAnnexYearDto.setYoyValue(new BigDecimal(lastValue));
                beforeAnnexYearDto.setYoyValue(new BigDecimal(beforeValue));

                //  37 这个指标是 （今年-去年）/去年  故指标值要重新赋值
                if (validIndexCodes3.contains(indicatorOverviewDto.getIndexCode())) {
                    BigDecimal tempYoyValue = new BigDecimal(yoyValue);
                    BigDecimal tempLastValue = new BigDecimal(lastValue);

                    curAnnexYearDto.setIndicatorValue(tempYoyValue);
                    lastAnnexYearDto.setIndicatorValue(tempLastValue);
                    beforeAnnexYearDto.setIndicatorValue(new BigDecimal(beforeValue));

                    indexDecimal = tempYoyValue;
                    lastDecimal = tempLastValue;

                    String otherYoyValue = calculateGrowthRate(yoyValue, lastValue);
                    String otherLastValue = calculateGrowthRate(lastValue, beforeValue);

                    String lastEndValue = calculateGrowthRate(previousYoyValue, lastEndYoyValue);
                    String otherBeforeValue = calculateGrowthRate(beforeValue, lastEndValue);

                    curAnnexYearDto.setYoyValue(new BigDecimal(otherYoyValue));
                    lastAnnexYearDto.setYoyValue(new BigDecimal(otherLastValue));
                    beforeAnnexYearDto.setYoyValue(new BigDecimal(otherBeforeValue));

                }


                //判断科室类型：临床非手术和临床手术 0：非手术科室   1：手术科室
                Integer type = departmentDto.getType();
                //分为两个大类  满分和非满分，非满分包含： 进步 退步 持平
                //判断是否获得满分
                if ("0".equals(dx) || "1".equals(dx)) {
                    //说明是上升指标  指标值越大越好
                    //该科室为非满分科室，非满分科室分为进步科室和退步科室，根据今年指标值和同比指标值比较即可
                    if (indexDecimal.compareTo(lastDecimal) > 0) {
                        if (type == 0) {
                            //进步非手术科室
                            dataDetail.getTableList5().add(annexDataDto);
                        } else {
                            //进步手术科室
                            dataDetail.getTableList6().add(annexDataDto);
                        }
                    } else if (indexDecimal.compareTo(lastDecimal) == 0) {
                        if (type == 0) {
                            //持平非手术科室
                            dataDetail.getTableList4().add(annexDataDto);
                        } else {
                            //持平手术科室
                            dataDetail.getTableList3().add(annexDataDto);
                        }
                    } else {
                        if (type == 0) {
                            //退步非手术科室
                            dataDetail.getTableList2().add(annexDataDto);
                        } else {
                            //退步手术科室
                            dataDetail.getTableList1().add(annexDataDto);
                        }
                    }

                } else if ("2".equals(dx)) {
                    //说明是下降指标(指标导向为 2)  指标值越小越好（小于满分值才能算获得满分）
                    //该科室为非满分科室，非满分科室分为进步科室和退步科室，根据今年指标值和同比指标值比较即可
                    if (indexDecimal.compareTo(lastDecimal) < 0) {
                        if (type == 0) {
                            //进步非手术科室
                            dataDetail.getTableList6().add(annexDataDto);
                        } else {
                            //进步手术科室
                            dataDetail.getTableList5().add(annexDataDto);
                        }
                    } else if (indexDecimal.compareTo(lastDecimal) == 0) {
                        if (type == 0) {
                            //持平非手术科室
                            dataDetail.getTableList4().add(annexDataDto);
                        } else {
                            //持平手术科室
                            dataDetail.getTableList3().add(annexDataDto);
                        }
                    } else {
                        if (type == 0) {
                            //退步非手术科室
                            dataDetail.getTableList2().add(annexDataDto);
                        } else {
                            //退步手术科室
                            dataDetail.getTableList1().add(annexDataDto);
                        }
                    }
                }
            }
            dataListDtoList.add(dataListDto);
        }
        return dataListDtoList;
    }


    /**
     * 计算同比时间
     *
     * @param
     * @param
     * @return
     */
    public List<String> getYoyTime(List<String> times) {
        List<String> lastYearDates = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        boolean isWholeMonth;
        // 使用流式操作按年份和月份分组,分组后的map中 键是年和月，如2024-01， 值是List集合，存的是相同年月的字符串,同时指定插入顺序，采用LinkedHashMap
        Map<String, List<String>> groupedDates = times.stream().collect(Collectors.groupingBy(date -> date.substring(0, 7), LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<String>> entry : groupedDates.entrySet()) {
            List<String> groupTimes = entry.getValue();
            // 判断是否是一整个月
            isWholeMonth = isWholeMonth(groupTimes);
            for (String currentDate : groupTimes) {
                LocalDate date = LocalDate.parse(currentDate, formatter);
                if (isWholeMonth) {
                    int lastYearMonthLength = date.minusYears(1).lengthOfMonth(); // 获取去年同月的天数
                    LocalDate lastYearStartDate = LocalDate.of(date.getYear() - 1, date.getMonth(), 1); // 去年同月的第一天
                    for (int i = 0; i < lastYearMonthLength; i++) {
                        lastYearDates.add(lastYearStartDate.plusDays(i).format(formatter));
                    }
                    break;
                } else {
                    LocalDate lastYearDate = date.minusYears(1);
                    lastYearDates.add(lastYearDate.format(formatter));
                }
            }
        }


        return lastYearDates;
    }

    //判断当前时间数组是否为一整个月
    private static boolean isWholeMonth(List<String> times) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate firstDate = LocalDate.parse(times.get(0), formatter);
        LocalDate lastDate = LocalDate.parse(times.get(times.size() - 1), formatter);
        if (firstDate.getDayOfMonth() != 1) {
            return false;
        }
        int daysInMonth = firstDate.lengthOfMonth();
        return lastDate.getDayOfMonth() == daysInMonth;
    }

    public String calculateGrowthRate(String currentValue, String previousValue) {
        if (currentValue.equals("-") || previousValue.equals("-")) {
            return "-"; // 当值为 "-" 时，无法计算增长率，直接返回 "-"
        }

        double current = Double.parseDouble(currentValue);
        double previous = Double.parseDouble(previousValue);

        if (previous == 0.0) {
            return "0"; // 当前值为非零而上一期值为零时,直接返回0，无意义
        }

        double growthRate = (current - previous) / previous;
        return String.format("%.2f", growthRate); // 将增长率转换为字符串，并返回,保留两位小数，四舍五入
    }


    public List<AnnexDataDto> otherAnnexMonitorData(IndicatorCalculateDto indicatorCalculateDto) {
        List<AnnexDataDto> annexDataDtoList = new ArrayList<>();

        Year currentYear = Year.now();//今年


        //查询所有指标
        List<IndicatorDataEntity> monitorIndicator = indicatorCalculateMapper.selectKeyIndicator(indicatorCalculateDto);
        //对所有涉及到的id进行去重
        List<String> elementIds = gatherCommonService.getAllElementIds(monitorIndicator);
        //查询元素定义表，确定元素数据来源 天表、月表、手填表等
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> dayTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "1".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> monthTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "2".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> handTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "3".equals(s.getDataTable())).collect(Collectors.toList());

        List<DepartmentIndicatorEntity> departmentIndicatorEntityList = new ArrayList<>();// 存放当前时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityLastList = new ArrayList<>();// 存放去年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityBeforeList = new ArrayList<>();// 存放前年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityPreviousList = new ArrayList<>();// 存放大前年时间的所有的天表、月表、手填表数据

        //查出天表数据 求的是指定时间区间的 天表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(dayTable)) {
            indicatorCalculateDto.setElementIds(dayTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> curDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityList.addAll(curDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> lastDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityLastList.addAll(lastDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> beforeDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityBeforeList.addAll(beforeDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> previousDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityPreviousList.addAll(previousDayData);
        }

        List<String> groupTimes;
        //查出月表数据 求的是指定时间区间的 月表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(monthTable)) {

            indicatorCalculateDto.setElementIds(monthTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> monthData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityList.addAll(monthData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> monthLastData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityLastList.addAll(monthLastData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> monthBeforeData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityBeforeList.addAll(monthBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> monthPreviousData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityPreviousList.addAll(monthPreviousData);

        }

        //查出手填表数据 求的是指定时间区间的 手填表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(handTable)) {
            indicatorCalculateDto.setElementIds(handTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<String> taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityList.addAll(handTableData);


            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableLastData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableLastData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityLastList.addAll(handTableLastData);



            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableBeforeData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableBeforeData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityBeforeList.addAll(handTableBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTablePreviousData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTablePreviousData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityPreviousList.addAll(handTablePreviousData);
        }

        Map<String, String> mapValue = new HashMap<>();
        Map<String, String> mapLastValue = new HashMap<>();
        Map<String, String> mapBeforeValue = new HashMap<>();
        Map<String, String> mapPreviousValue = new HashMap<>();
        mapValue = departmentIndicatorEntityList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapLastValue = departmentIndicatorEntityLastList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapBeforeValue = departmentIndicatorEntityBeforeList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapPreviousValue = departmentIndicatorEntityPreviousList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));

        for (IndicatorDataEntity entity : monitorIndicator) {
            //解析当前指标的公式，通过元素值计算指标值
            String formula = entity.getCalculationFormulaId();
            String indexValue = Calculator.conversionToSting(formula, mapValue);
            String indexLastValue = Calculator.conversionToSting(formula, mapLastValue);
            String indexBeforeValue = Calculator.conversionToSting(formula, mapBeforeValue);
            String indexPreviousValue = Calculator.conversionToSting(formula, mapPreviousValue);


            AnnexYearDto annexYearDto = new AnnexYearDto();
            AnnexYearDto lastAnnexYearDto = new AnnexYearDto();
            AnnexYearDto beforeAnnexYearDto = new AnnexYearDto();

            //  设置近三年满分值
            annexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            lastAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            beforeAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));

            //  设置近三年指标值
            BigDecimal indexDecimal = new BigDecimal(indexValue.equals("-") ? "0" : indexValue);
            BigDecimal lastDecimal = new BigDecimal(indexLastValue.equals("-") ? "0" : indexLastValue);
            BigDecimal beforeDecimal = new BigDecimal(indexBeforeValue.equals("-") ? "0" : indexBeforeValue);
            annexYearDto.setIndicatorValue(indexDecimal);
            lastAnnexYearDto.setIndicatorValue(lastDecimal);
            beforeAnnexYearDto.setIndicatorValue(beforeDecimal);

            //设置近三年时间
            annexYearDto.setTime(currentYear.toString());
            lastAnnexYearDto.setTime(currentYear.minusYears(1).toString());
            beforeAnnexYearDto.setTime(currentYear.minusYears(2).toString());


            //设置近三年同比增幅
            String yoyValue = calculateGrowthRate(indexValue, indexLastValue);
            String lastYoyValue = calculateGrowthRate(indexLastValue, indexBeforeValue);
            String beforeYoyValue = calculateGrowthRate(indexBeforeValue, indexPreviousValue);
            annexYearDto.setYoyValue(new BigDecimal(yoyValue.equals("-") ? "0" : yoyValue));
            lastAnnexYearDto.setYoyValue(new BigDecimal(lastYoyValue.equals("-") ? "0" : lastYoyValue));
            beforeAnnexYearDto.setYoyValue(new BigDecimal(beforeYoyValue.equals("-") ? "0" : beforeYoyValue));


            AnnexDataDto annexDataDto = new AnnexDataDto();
            annexDataDto.setDeptName(indicatorCalculateDto.getUserInfo().getWardName());
            annexDataDto.setIndicatorName(entity.getIndexName());
            annexDataDto.setIndicatorUnit(entity.getIndexUnit());
            annexDataDto.setIndicatorXh(entity.getRank());
            annexDataDto.setLeader(entity.getFgld());
            annexDataDto.setResponsibleDepartment(entity.getZrbm());
            annexDataDto.getAnnexYearDtos().add(annexYearDto);
            annexDataDto.getAnnexYearDtos().add(lastAnnexYearDto);
            annexDataDto.getAnnexYearDtos().add(beforeAnnexYearDto);

            annexDataDtoList.add(annexDataDto);

        }
        return annexDataDtoList;
    }

    public List<AnnexDataDto> otherAnnexCommonData(IndicatorCalculateDto indicatorCalculateDto) {
        List<AnnexDataDto> annexDataDtoList = new ArrayList<>();

        Year currentYear = Year.now();//今年


        //查询所有指标
        List<IndicatorDataEntity> monitorIndicator = indicatorCalculateMapper.selectUnKeyIndicator(indicatorCalculateDto);
        //对所有涉及到的id进行去重
        List<String> elementIds = gatherCommonService.getAllElementIds(monitorIndicator);
        //查询元素定义表，确定元素数据来源 天表、月表、手填表等
        List<ElementDataEntity> elementDataEntities = elementDataMapper.query(elementIds);
        //分别得出天表，月表，手填表的元素数据
        List<ElementDataEntity> dayTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "1".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> monthTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "2".equals(s.getDataTable())).collect(Collectors.toList());
        List<ElementDataEntity> handTable = elementDataEntities.stream().filter(s -> StringUtils.isNotBlank(s.getDataTable()) && "3".equals(s.getDataTable())).collect(Collectors.toList());

        List<DepartmentIndicatorEntity> departmentIndicatorEntityList = new ArrayList<>();// 存放当前时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityLastList = new ArrayList<>();// 存放去年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityBeforeList = new ArrayList<>();// 存放前年时间的所有的天表、月表、手填表数据
        List<DepartmentIndicatorEntity> departmentIndicatorEntityPreviousList = new ArrayList<>();// 存放大前年时间的所有的天表、月表、手填表数据

        //查出天表数据 求的是指定时间区间的 天表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(dayTable)) {
            indicatorCalculateDto.setElementIds(dayTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> curDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityList.addAll(curDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> lastDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityLastList.addAll(lastDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> beforeDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityBeforeList.addAll(beforeDayData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> previousDayData = indicatorCalculateMapper.queryEscalationGroupByYear(indicatorCalculateDto); //天表数据
            departmentIndicatorEntityPreviousList.addAll(previousDayData);
        }

        List<String> groupTimes;
        //查出月表数据 求的是指定时间区间的 月表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(monthTable)) {

            indicatorCalculateDto.setElementIds(monthTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));
            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<DepartmentIndicatorEntity> monthData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityList.addAll(monthData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            List<DepartmentIndicatorEntity> monthLastData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityLastList.addAll(monthLastData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            List<DepartmentIndicatorEntity> monthBeforeData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityBeforeList.addAll(monthBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            List<DepartmentIndicatorEntity> monthPreviousData = indicatorCalculateMapper.queryEscalationNewByYear(indicatorCalculateDto); //月表数据
            departmentIndicatorEntityPreviousList.addAll(monthPreviousData);

        }

        //查出手填表数据 求的是指定时间区间的 手填表数据之和
        if (!org.springframework.util.CollectionUtils.isEmpty(handTable)) {
            indicatorCalculateDto.setElementIds(handTable.stream().map(ElementDataEntity::getId).collect(Collectors.toList()));

            indicatorCalculateDto.setQueryYear(currentYear.toString());
            List<String> taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityList.addAll(handTableData);


            indicatorCalculateDto.setQueryYear(currentYear.minusYears(1).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableLastData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableLastData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityLastList.addAll(handTableLastData);


            indicatorCalculateDto.setQueryYear(currentYear.minusYears(2).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTableBeforeData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTableBeforeData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityBeforeList.addAll(handTableBeforeData);

            indicatorCalculateDto.setQueryYear(currentYear.minusYears(3).toString());
            taskIds = reportTaskMapper.selectReportTasksByYear(indicatorCalculateDto);
            List<DepartmentIndicatorEntity> handTablePreviousData = new ArrayList<>();
            if (taskIds.size() > 0) {
                indicatorCalculateDto.setTaskIds(taskIds);
                handTablePreviousData = reportMapper.queryAnalysisReportByYear(indicatorCalculateDto); //手填表数据
            }
            departmentIndicatorEntityPreviousList.addAll(handTablePreviousData);
        }

        Map<String, String> mapValue = new HashMap<>();
        Map<String, String> mapLastValue = new HashMap<>();
        Map<String, String> mapBeforeValue = new HashMap<>();
        Map<String, String> mapPreviousValue = new HashMap<>();
        mapValue = departmentIndicatorEntityList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapLastValue = departmentIndicatorEntityLastList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapBeforeValue = departmentIndicatorEntityBeforeList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));
        mapPreviousValue = departmentIndicatorEntityPreviousList.stream().collect(Collectors.groupingBy(e -> String.format("${%s}", e.getId()), Collectors.collectingAndThen(Collectors.summingDouble(e -> Double.parseDouble(e.getElementNumber())), sum -> String.valueOf(sum))));

        for (IndicatorDataEntity entity : monitorIndicator) {
            //解析当前指标的公式，通过元素值计算指标值
            String formula = entity.getCalculationFormulaId();
            String indexValue = Calculator.conversionToSting(formula, mapValue);
            String indexLastValue = Calculator.conversionToSting(formula, mapLastValue);
            String indexBeforeValue = Calculator.conversionToSting(formula, mapBeforeValue);
            String indexPreviousValue = Calculator.conversionToSting(formula, mapPreviousValue);


            AnnexYearDto annexYearDto = new AnnexYearDto();
            AnnexYearDto lastAnnexYearDto = new AnnexYearDto();
            AnnexYearDto beforeAnnexYearDto = new AnnexYearDto();

            //  设置近三年满分值
            annexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            lastAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));
            beforeAnnexYearDto.setFullValue(new BigDecimal(entity.getMfz()));

            //  设置近三年指标值
            BigDecimal indexDecimal = new BigDecimal(indexValue.equals("-") ? "0" : indexValue);
            BigDecimal lastDecimal = new BigDecimal(indexLastValue.equals("-") ? "0" : indexLastValue);
            BigDecimal beforeDecimal = new BigDecimal(indexBeforeValue.equals("-") ? "0" : indexBeforeValue);
            annexYearDto.setIndicatorValue(indexDecimal);
            lastAnnexYearDto.setIndicatorValue(lastDecimal);
            beforeAnnexYearDto.setIndicatorValue(beforeDecimal);

            //设置近三年时间
            annexYearDto.setTime(currentYear.toString());
            lastAnnexYearDto.setTime(currentYear.minusYears(1).toString());
            beforeAnnexYearDto.setTime(currentYear.minusYears(2).toString());


            //设置近三年同比增幅
            String yoyValue = calculateGrowthRate(indexValue, indexLastValue);
            String lastYoyValue = calculateGrowthRate(indexLastValue, indexBeforeValue);
            String beforeYoyValue = calculateGrowthRate(indexBeforeValue, indexPreviousValue);
            annexYearDto.setYoyValue(new BigDecimal(yoyValue.equals("-") ? "0" : yoyValue));
            lastAnnexYearDto.setYoyValue(new BigDecimal(lastYoyValue.equals("-") ? "0" : lastYoyValue));
            beforeAnnexYearDto.setYoyValue(new BigDecimal(beforeYoyValue.equals("-") ? "0" : beforeYoyValue));


            AnnexDataDto annexDataDto = new AnnexDataDto();
            annexDataDto.setDeptName(indicatorCalculateDto.getUserInfo().getWardName());
            annexDataDto.setIndicatorName(entity.getIndexName());
            annexDataDto.setIndicatorUnit(entity.getIndexUnit());
            annexDataDto.setIndicatorXh(entity.getRank());
            annexDataDto.setLeader(entity.getFgld());
            annexDataDto.setResponsibleDepartment(entity.getZrbm());
            annexDataDto.getAnnexYearDtos().add(annexYearDto);
            annexDataDto.getAnnexYearDtos().add(lastAnnexYearDto);
            annexDataDto.getAnnexYearDtos().add(beforeAnnexYearDto);

            annexDataDtoList.add(annexDataDto);

        }
        return annexDataDtoList;
    }
}
